如何以角度访问 *ngFor 中 FormGroup 的 formArray?

may*_*iya 3 angular formarray formgroups angular-abstract-control

我正在使用 FormArray 来使用嵌套 FormControl。我的表格是这样的:

let form = new FormGroup({
   name: new FormControl(),
   email: new FormControl(),
   Addresses : new FormArray([
      new FormGroup({
         building: new FormControl(),
         society : new FormControl(),
      }),
      new FormGroup({
         building: new FormControl(),
         society : new FormControl(),
      })
      new FormGroup({
         building: new FormControl(),
         society : new FormControl(),
      })
   ])
})



addNewAddress() {
   let newAddress = new FormGroup({
      building: new FormControl(),
      society : new FormControl(),
   });
   this.form.get("addresses").push(newAddress)
}
Run Code Online (Sandbox Code Playgroud)

并在 HTML 模板中

<div *ngFor="let controlGroup of form.get('addresses').controls; let i=index">
   <ng-container [formGroup]="controlGroup">
     <input type="text" formControlName="building" />
     <input type="text" formControlName="society" />
   </ng-container>
</div>
Run Code Online (Sandbox Code Playgroud)

**但是上面的代码返回Build Error类似抽象控件上不存在的控件。**

所以我转而form.get('addresses')使用FormControl这种吸气方法。

get addressArray() : FormArray {
    return form.get('addresses') as FormArray
}
//And use it in HTML like this

<div *ngFor="let controlGroup of addressArray.controls; let i=index">
   <ng-container [formGroup]="controlGroup">                             <== now here is build error
     <input type="text" formControlName="building" />
     <input type="text" formControlName="society" />
   </ng-container>
</div>
Run Code Online (Sandbox Code Playgroud)

在那次转换之后。新的构建错误提出了这一点controlGroup does not contain this methods : addControl, removeCotnrol and ...

因为addressArray.**controls**返回数组abstractControl而不是FormControland[formGroup]指令需要FormControl

我怎样才能像这样定义类型*ngFor

let (controlGroup: FormControl) of addressArray.controls; let i=index
Run Code Online (Sandbox Code Playgroud)

这可能吗?

请帮我。

may*_*iya 6

您可以按照与使用相同的方式将其与 Type 一起使用addressArray.controls

这是完整的代码:

let form = new FormGroup({
   name: new FormControl(),
   email: new FormControl(),
   Addresses : new FormArray([
      new FormGroup({
         building: new FormControl(),
         society : new FormControl(),
      }),
      new FormGroup({
         building: new FormControl(),
         society : new FormControl(),
      })
      new FormGroup({
         building: new FormControl(),
         society : new FormControl(),
      })
   ])
})



addNewAddress() {
   let newAddress = new FormGroup({
      building: new FormControl(),
      society : new FormControl(),
   });
   this.form.get("addresses").push(newAddress)
}

get addressArray() : FormArray {
    return form.get('addresses') as FormArray
}

get addressControlsArray() : FormGroup[] {
    return this.addressArray.controls as FormGroup[]
}
Run Code Online (Sandbox Code Playgroud)

在 HTML 中

<div *ngFor="let controlGroup of addressControlsArray; let i=index">
   <ng-container [formGroup]="controlGroup">
     <input type="text" [formControlName]="building" />
     <input type="text" [formControlName]="society" />
   </ng-container>
</div>
Run Code Online (Sandbox Code Playgroud)

您可以迭代所有 formField 来clear all it's validator像这样:

nestedFormFieldIterator(formGroup: FormGroup | FormArray, action: "ClearValidation" | "MarkAsDirty"): void {
    Object.keys(formGroup.controls).forEach(key => {
      const control = formGroup.controls[key] as FormControl | FormGroup | FormArray;
      if (control instanceof FormControl) {
        // console.log(`Clearing Validators of ${key}`);
        if (action == "ClearValidation") {
          control.clearValidators();
        }
        if (action == "MarkAsDirty") {
          control.markAsDirty();
        }
        control.updateValueAndValidity();
      } else if (control instanceof FormGroup || control instanceof FormArray) {
        // console.log(`control '${key}' is nested group or array. calling clearValidators recursively`);
        this.nestedFormFieldIterator(control, action);
      }
    });
  }
Run Code Online (Sandbox Code Playgroud)