Angular 5 - 如何填充FormArray

问题描述 投票:0回答:1

我将填写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的值不会刷新。

angular-material angular5
1个回答
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);
     });
© www.soinside.com 2019 - 2024. All rights reserved.