使用Formgroup.reset()将FormGroup重置为预定义状态

时间:2018-01-26 15:29:08

标签: angular

在我的Angular 2组件中,我使用Formgroup和18 AbstractControl s。用户可以编辑从数据库加载的配置文件。 我想添加一个Reset - 按钮,将表单重置为原始状态(显然)。但是,使用this.form.reset()清除所有字段。我可以通过调用AbstractControl重置FormGroup中的特定reset({firstname: 'Jack'});。 是否可以将FormGroup重置的状态更改为?

2 个答案:

答案 0 :(得分:1)

创建表单初始化函数,并在重置后调用它

component.html

<form [formGroup]="profileForm">
  <input formControlName="firstname" class="form-control">

  <button class="btn" type="submit">Submit </button>
  <button class="btn" type="button" (click)="onReset()">Reset </button>
</form>

Component.ts

  profileForm: FormGroup;

  profile  = {
    firstname: 'name'
  }
  constructor(private formBuilder: FormBuilder) { }
  ngOnInit() {
    this.initForm();

  }

  initForm() {

    this.profileForm = this.formBuilder.group({
      firstname: [this.profile.firstname, Validators.required]
    });
  }
  onReset() {
    this.profileForm.reset();
    this.initForm();
  }

答案 1 :(得分:1)

如果您构建(或已构建)表单,profile对象与表单组中的属性匹配,则可以调用:

this.profileForm.reset(this.profile);

例如:

profile = {firstname: 'first name'};

// ...

this.profileForm = this.formBuilder.group({
  firstname: [this.profile.firstname],
});

// ...

this.profileForm.reset(this.profile)

使用模板:

<form [formGroup]="profileForm">
  <input formControlName="firstname" />
</form>

<强> DEMO