Angular 5 - 如何填充FormArray

时间:2018-03-02 14:23:42

标签: angular-material angular5

我将填写customerNumberContainers,如下所示:

this.form = new FormGroup({    
    customerNumberContainers: new FormArray([
      new FormGroup({
        contactTenant: new FormControl('', [Validators.required, Validators.minLength(2)]),
        customerNumber: new FormControl('', [Validators.required, Validators.minLength(2)])
        }),
    ]),

因此,在获得

之后,我会这样做
this.contactService.findContactById(this.id).subscribe(response => { ...

将值设置为表格:

let customerNumberContainersFormArray: FormArray = this.form.controls.customerNumberContainers as FormArray;
customerNumberContainersFormArray.controls["0"].controls.contactTenant.value = 'TestValue';

但未显示:

in Controller:
get customerNumberContainers(): FormArray {
    return this.form.get("customerNumberContainers") as FormArray;
  } 

in Template:
<div formArrayName="customerNumberContainers">
    <div *ngFor="let customerNumberContainer of customerNumberContainers.controls; index as i" [formGroupName]="i">
        <mat-input-container class="full-width-input">
        <input matInput formControlName="contactTenant">
    </mat-input-container> 
</div>

有谁知道我做错了什么。对我来说,带有* ngFor的值不会刷新。

1 个答案:

答案 0 :(得分:0)

为什么不用模型修补整个表格?像这样:

设置模型,例如:

export class Tenants {
  id: number;
  customerNumberContainers: TenantContact[];
}
export class TenantContact {
  contactTenant: string;
  customerNumber: string;
}

从服务中获取它,就像你一直这样,但它应匹配上面的模型并修补整个表单(或setValue)

this.contactService.findContactById(this.id).subscribe((tenats: Tenants) => {
      this.form.patchValue(tenats);
     });