提交后重新设置角度2中的表单

前端之家收集整理的这篇文章主要介绍了提交后重新设置角度2中的表单前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我知道Angular 2目前没有办法轻松地将表单重置为原始状态.在我周围找到一个解决方案,像下面的那样重置表单域.

有人建议,我需要删除控制组,并创建一个新的,以重建表单为原则.我很难弄清楚最好的方式来做到这一点.我知道我需要在一个函数中包装表单,但是在构造函数中这样做时我遇到错误.

什么是重建控制组以完全重置表单的最佳方式?

class App {

    name: Control;
    username: Control;
    email: Control;

    form: ControlGroup;

    constructor(private builder: FormBuilder) {

        this.name = new Control('',Validators.required);
        this.email = new Control('',Validators.required);
        this.username = new Control('',Validators.required);

        this.form = builder.group({
            name: this.name,email: this.email,username: this.username
        });
    }

    onSubmit(value: any): void {  
        // code that happens when form is submitted
        // then reset the form
        this.reset();
    }

    reset() {
        for (let name in this.form.controls) {
            this.form.controls[name].updateValue('');
            this.form.controls[name].setErrors(null);
        }
    }
}

解决方法

RC.6

支持重置表单并保持提交状态.

console.log(this.form.submitted);
this.form.reset()

要么

this.form = new FormGroup()...;

更新

要更新一些仅在创建表单时初始化的内容,需要进行一些额外的测量

<form *ngIf="showForm"

  showForm:boolean = true;
  onSubmit(value:any):void {
    this.showForm = false;
    setTimeout(() => {
    this.reset()
      this.showForm = true;
    });
  }

Plunker example

原始< = RC.5
只需将创建表单的代码移动到一个方法,并在处理提交后再次调用它:

@Component({
  selector: 'form-component',template: `
    <form (ngSubmit)="onSubmit($event)" [ngFormModel]="form">
       <input type="test" ngControl="name">
       <input type="test" ngControl="email">
       <input type="test" ngControl="username">
       <button type="submit">submit</button>
    </form>
    <div>name: {{name.value}}</div>
    <div>email: {{email.value}}</div>
    <div>username: {{username.value}}</div>
`
})
class FormComponent {

  name:Control;
  username:Control;
  email:Control;

  form:ControlGroup;

  constructor(private builder:FormBuilder) {
    this.createForm();
  }

  createForm() {
    this.name = new Control('',Validators.required);
    this.email = new Control('',Validators.required);
    this.username = new Control('',Validators.required);

    this.form = this.builder.group({
      name: this.name,username: this.username
    });
  }

  onSubmit(value:any):void {
    // code that happens when form is submitted
    // then reset the form
    this.reset();
  }

  reset() {
    this.createForm();
  }
}

Plunker example

原文链接:https://www.f2er.com/html/230401.html

猜你在找的HTML相关文章