使用表单数组和 *ngFor语言 - 角度 2/5 将输入字段添加到表中



我是 Angular 5 的初学者,尝试将输入字段动态添加到带有表单数组的表中。 我在 tr 标签中使用了 *ngFor,示例代码如下:

文件:

<table class="table">
<thead>
<tr>
<th>F1</th>
<th>F2</th>
</tr>
</thead>
<form novalidate role="form" [formGroup]="caseinfo">
<div formArrayName="caseRows">
<tbody>
<tr *ngFor="let caserow of caseinfo.controls.caseRows.controls; let i=index" [formGroupName]="i" >
<td>
<div class="form-group">
<input type="text" class="form-control" formControlName="caselpn">
</div>
</div>
</td>
<td>
<div class="form-group">
<input type="text" class="form-control" formControlName="casesku">
</div>
</td>
</tr>
</tbody>
</div>
</form>
</table>

TS 文件:

initFormCase()
{
this.caseinfo = this.fb.group({
caseRows: this.fb.array([this.initCaseRows()]) // here
});
}
initCaseRows() {
return this.fb.group({
caselpn:[null, Validators.compose([
Validators.required,
])],
casesku:[null, Validators.compose([
Validators.required,
])]
});
}

这是我的输出的样子: https://i.stack.imgur.com/rd5A1.png

预期产出: F1 列下的输入字段 1。和 F2 列下的输入字段 2。

注意: 我也尝试更换身体内部的 ngFor。没有运气。 提前感谢! 抱歉,无法发布图像,因为我的代表积分较低。

您的HTML结构错误,请尝试按如下方式更新并检查

<form novalidate role="form" [formGroup]="caseinfo">
<div formArrayName="caseRows">
<table class="table">
<thead>
<tr>
<th>F1</th>
<th>F2</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let caserow of caseinfo.controls.caseRows.controls; let i=index" [formGroupName]="i">
<td>
<div class="form-group">
<input type="text" class="form-control" formControlName="caselpn">
</div>
</td>
<td>
<div class="form-group">
<input type="text" class="form-control" formControlName="casesku">
</div>
</td>
</tr>
</tbody>
</table>
</div>
</form>

最新更新