首页 > 解决方案 > 角度反应形式在保存后删除 formArray 元素

问题描述

在 Angular 5 中,我有一个表单,用户可以添加多个可以一次保存的费用记录。保存后需要删除这些记录并返回一行的初始状态。我已经尝试过以下代码,它进入初始状态,但是当返回到该状态时验证正在触发。

ngOnInit() {
    this.fastPostingForm = this.fb.group({
      Charges: this.fb.array([
        this.initCharge()
      ])
    });
}

initCharge() {
    return this.fb.group({
      room: ['', Validators.required],
      transactionCode: ['', Validators.required],
      amount: ['', Validators.required],
      quantity: [1, [Validators.required, Validators.min(1), Validators.max(9999)]],
      window: ['', Validators.required],
      reservationId: [''],
      rsv:[{}]
    });
  }

  addCharge() {
    const control = <FormArray>this.fastPostingForm.controls['Charges'];
    control.push(this.initCharge());
    console.log(control.length);
  }

 saveForm(){
        //save process

        //clear form and remove form array elements

        this.fastPostingForm = this.fb.group({
      Charges: this.fb.array([
        this.initCharge()
      ])
    });

  }

在 UI 中,每个控件都使用以下条件进行验证。

 <mat-error *ngIf="!fastPostingForm.controls.Charges.controls[i].controls.room.valid && fastPostingForm.controls.Charges.controls[i].controls.room.touched">message
</mat-error

>

标签: angularangular-reactive-forms

解决方案


尝试这个

saveForm(){

 this.fastPostingForm = this.fb.group({
      Charges: this.fb.array([
        this.initCharge()
 ])
 this.fastPostingForm.markAsUntouched();
 this.fastPostingForm.markAsPristine();
 this.fastPostingForm.updateValueAndValidity();

 });

推荐阅读