【发布时间】:2020-11-09 13:53:49
【问题描述】:
动态创建和删除表中的行。
问题:
- 出现控制台错误:“错误:找不到名称为‘vilats’的控件”
- 在输入框中添加一些值后,可以使用按钮添加和删除。
用于创建动态表格的 HTML 代码。
<form class="form-horizontal" [formGroup]="loanProductForm" (ngSubmit)="onSubmit()">
<table>
<thead>
<tr>
<th>BP</th>
<th>PULSE</th>
<th>TEMP.</th>
<th>Wt.</th>
<th>Ht.</th>
<th></th>
</tr>
</thead>
<tbody>
<tr [formGroupName]="i" formArrayName="vilats" *ngFor="let product of loanProductForm.get('vitals').controls; let i = index ; let last = last">
<td>
<input class="form-control form-control-sm" type="text" id="newAttributeBp"
formControlName="BP" />
</td>
<td>
<input class="form-control form-control-sm" type="text" id="newAttributePulse"
formControlName="PULSE" />
</td>
<td>
<input class="form-control form-control-sm" type="text" id="newAttributeTemp"
formControlName="Temp"/>
</td>
<td>
<input class="form-control form-control-sm" type="text" id="newAttributeWeight"
formControlName="Wt"/>
</td>
<td>
<input class="form-control form-control-sm" type="text" id="newAttributeHeight"
name="newAttributeHeight" formControlName="Ht"/>
</td>
<td>
<button *ngIf="last" class="btn btn-sm btn-default" type="button" (click)="addProductButtonClick()"
title="Add New"><i class="fas fa-plus"></i></button>
<button (click)="removeCompany(i)" *ngIf="!last" class="btn btn-sm btn-default"
title="Delete"><i class="fas fa-trash-alt"></i></button>
</td>
</tr>
</tbody>
</table>
<input type="submit" value="Save"/>
</form>
用于初始化、添加和删除条目的组件代码。
loanProductForm: FormGroup;
ngOnInit() {
this.loanProductForm = this._formBuilder.group({
vitals: this._formBuilder.array([this.addProductFormGroup()])
});
}
addProductFormGroup(): FormGroup {
return this._formBuilder.group({
entryDate: ["", Validators.required],
BP: ["", Validators.required],
PULSE: ["", Validators.required],
Temp: ["", Validators.required],
Wt: ["", Validators.required],
Ht: ["", Validators.required]
});
}
addProductButtonClick(): void {
(<FormArray>this.loanProductForm.get("vitals")).push(
this.addProductFormGroup()
);
}
在此处复制问题stackblitz
【问题讨论】:
标签: angular typescript angular8