我试图显示以前添加的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'的控件
仅第二个元素显示在模板中,而不显示第一个元素,我想显示所有添加的元素以显示在模板中。任何帮助。我刚接触角
答案 0 :(得分:0)
在Component.ts中,将get语句添加到公司ip地址表单数组中,如下所示:
get companyIpAddressFormArray() { return (<FormArray>this.companyForm.get('company_ip_addresses')) ; }
现在在HTML中,将ngFor语句修改为
*ngFor="let item of companyIpAddressFormArray.controls"
希望这会起作用