Angular 使用FormGroup.Reset()将FormGroup重置为预定义状态

Angular 使用FormGroup.Reset()将FormGroup重置为预定义状态,angular,Angular,在我的Angular 2组件中,我使用了带有18个AbstractControl的Formgroup。用户可以编辑从数据库加载的配置文件。 我想添加一个Reset-按钮,将表单重置为其原始状态(显然)。但是,使用this.form.reset()会清除所有字段。我可以通过调用reset({firstname:'Jack'),在FormGroup中重置特定的AbstractControl。 是否可以更改其重置为的FormGroup的状态?创建表单初始化函数,并在重置后调用它 component.h

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

是否可以更改其重置为的
FormGroup
的状态?

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

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>
如果您构建(或已经构建)表单,并且
profile
对象与表单组中的属性相匹配,则可以调用:

this.profileForm.reset(this.profile);
例如:

profile={firstname:'firstname'};
// ...
this.profileForm=this.formBuilder.group({
名字:[this.profile.firstname],
});
// ...
this.profileForm.reset(this.profile)
使用模板:



只需重新初始化整个表单,就像对
FormGroup
中的每个特定
AbstractControl
使用
reset
一样。这就是我想要避免的,因为它很难看。在我看来,这就是
reset()
的作用。在表单初始化时,您可以为每个表单控件声明默认值,只需修改该变量即可。我使用以下代码初始化表单:
this.profileForm=this.formBuilder.group({firstname:[this.profile.firstname,Validators.required]})
这是不是正确?您将配置文件.firstname初始化为什么?您试图将表单重置为什么?非常好,它必须简单明了。谢谢您的欢迎,很高兴听到它符合您的要求。祝你今天愉快!:)
  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();
  }