【发布时间】:2019-05-06 16:35:55
【问题描述】:
我正在尝试显示之前添加的 formarray 值。
component.ts
this.companyForm = this.fb.group({
id: [],
company_details: this.fb.group({
----
}),
company_ip_addresses: this.fb.array([this.fb.group({
start_ip: new FormControl(),
end_ip: new FormControl()
})]),
});
addItem(): void {
let control = <FormArray>this.companyForm.controls.company_ip_addresses;
control.push(this.fb.group({
start_ip: new FormControl(),
end_ip: new FormControl()
}));
}
deletefield(index){
let control = <FormArray>this.companyForm.controls.company_ip_addresses;
control.removeAt(index)
}
component.html
<div formArrayName="company_ip_addresses">
<div *ngFor="let item of companyForm.get('company_ip_addresses').controls; let i=index; let isFirst = first">
<ng-container [formGroupName]="i">
<div fxLayout="row wrap" fxLayoutAlign="space-around center">
<div fxFlex="30">
<mat-form-field class="example-full-width" class="w-90-p">
<input matInput placeholder="START IP" formControlName="start_ip">
</mat-form-field>
</div>
<div fxFlex="30">
<mat-form-field class="example-full-width" class="w-90-p">
<input matInput placeholder="END IP" formControlName="end_ip">
</mat-form-field>
</div>
<div fxFlex="30">
<div *ngIf="isFirst;then addfield else delete">
</div>
<ng-template #addfield>
<button mat-icon-button class="text-center" (click)="addItem()">
<mat-icon class="font-weight-900">add</mat-icon>
</button>
</ng-template>
<ng-template #delete>
<button mat-icon-button class="text-center" (click)="deletefield(i)">
<mat-icon class="font-weight-900 red-500-fg">delete</mat-icon>
</button>
</ng-template>
</div>
</div>
</ng-container>
</div>
</div>
API 对该 formArray 的响应如下:
company_ip_addresses: Array(2)
0: {id: 1, start_ip: "111.111.111.1", end_ip: "123.123.123.1", created_by: 18, modified_by: 18, …}
1: {id: 2, start_ip: "111.111.111.2", end_ip: "111.111.111.3", created_by: 18, modified_by: 18, …}
在形成 PatchValue 之前,我正在绑定数据,如下所示:
this.companyForm.controls.company_ip_addresses = this.fb.array([new FormControl()]);
let ip_addresses = this.companyForm.get('company_ip_addresses') as FormArray;
for (let i = 1; i < this.companyData.viewData.company_ip_addresses.length; i++) {
//ip_addresses.push(new FormControl(''));
ip_addresses.push(this.fb.group({
start_ip: new FormControl(''),
end_ip: new FormControl('')
}));
}
this.companyForm.patchValue(this.companyData.viewData);
将错误显示为: 找不到带有路径的控件:'company_ip_addresses -> 0 -> end_ip'
模板中只显示第二个元素,但不显示第一个元素,我想显示要在模板中显示的所有添加元素。任何帮助。我是角度新手
【问题讨论】:
标签: angular form-control formarray