属性'Rows'来自索引签名,因此必须使用 ['Rows'] 访问它



我正在尝试使用FormArray,但遇到错误:

属性"Rows"来自索引签名,因此必须使用['Rows']访问它。

*ngFor="let itemrow of invoiceForm.controls.Rows.controls"

HTML文件:

<form [formGroup]="invoiceForm">
<table border=1>
<thead>
<th>Id</th>
<th>Name</th>
<th>Action</th>
</thead>
<tbody formArrayName="Rows">
<tr *ngFor="let itemrow of invoiceForm.controls.Rows.controls; let i=index;let l=last"
[formGroupName]="i">
<td>{{i+1}}</td>
<td>
<mat-form-field  appearance="fill">
<mat-label>Input</mat-label>
<input matInput formControlName="name" class="form-control">
</mat-form-field>
</td>
<td>
<button *ngIf="invoiceForm.controls.Rows.controls.length > 1" (click)="deleteRow(i)" class="btn btn-danger">Delete</button>
</td>
</tr>
</tbody>
</table>
</form>
<button type="button" (click)="addNewRow()" class="btn btn-primary">Add new Row</button>
<br/>
<br/>

TS文件:

public invoiceForm!: FormGroup;
constructor(private _fb: FormBuilder) {}
ngOnInit() {
this.invoiceForm = this._fb.group({
Rows: this._fb.array([this.initRows()])
});
}
get formArr() {
return this.invoiceForm.get("Rows") as FormArray;
}
initRows() {
return this._fb.group({
name: [""]
});
}
addNewRow() {
this.formArr.push(this.initRows());
}
deleteRow(index: number) {
this.formArr.removeAt(index);
}

由于您为formArrFormArray实现了getter

get formArr() {
return this.invoiceForm.get("Rows") as FormArray;
}

您可以重用getter,如下所示(在HTML中(:

<tr *ngFor="let itemrow of formArr.controls; let i=index;let l=last"
[formGroupName]="i">
...
</tr>
<button *ngIf="formArr.controls.length > 1" (click)="deleteRow(i)" class="btn btn-danger">Delete</button>

相关内容

  • 没有找到相关文章

最新更新