使用Angular4 ReactiveForm创建表单(我正在使用的版本) . 我在哪里有一个表格,其中包含代码,年份和类别列表 .
主要表格:
-
代码
-
年
-
分类[]
-
代码
-
描述
-
订单
-
产品[]
-
代码
-
描述
-
价格
但我正在尝试以下列方式显示表单,其中类别列表和每个类别中的产品将是所有行,并且将全部显示在同一个表中(示例):
<input code>
<input year>
<table>
<tr>Category 1</tr>
<tr>Product 1.1</tr>
<tr>Product 1.2</tr>
<tr>Product 1.3</tr>
<tr>Category 2</tr>
<tr>Product 2.1</tr>
<tr>Product 2.2</tr>
</table>
<button addNewCategory />
<button addNewProduct />
我能够将类别显示为行,但我无法将每个类别中的产品显示为类别行下方的行:
我的打字稿形式:
ngOnInit() {
this.form = this._fb.group({
code: ['', Validators.required],
year: ['', Validators.required],
categories: this._fb.array([this.initCategory()])
});
}
initCategory() {
return this._fb.group({
code: ['', Validators.required],
desc: ['', Validators.required],
order: ['', Validators.required],
products: this._fb.array([this.initProduct()])
});
}
initProduct() {
return this._fb.group({
code: ['', Validators.required],
desc: ['', Validators.required],
price: ['', Validators.required]
});
}
搜索时,我被告知使用ngfor模板,但我无法使用它们,当我尝试使用它们时,模板标签内的内容不会显示 .
如果我使用div,我可以在每个类别下面显示产品 . 但它在表格中表现不佳 .
我的模板:
<div>
<form [formGroup]="form">
<input type="text" formControlName="code" />
<input type="text" formControlName="year" />
<table>
<div formArrayName="categories">
<template *ngFor="let category of form.controls['categories'].controls; let i=index">
<tr>
<td><input type="text" formControlName="code" /></td>
<td><input type="text" formControlName="desc" /></td>
<td><input type="text" formControlName="order" /></td>
</tr>
<div="products">
<template *ngFor="let product of category.controls['products'].controls; let j=index">
<tr>
<td><input type="text" formControlName="code" /></td>
<td><input type="text" formControlName="desc" /></td>
<td><input type="text" formControlName="price" /></td>
</tr>
</template>
</div>
</template>
</div>
</table>
</form>
</div>
1 回答
首先,您应该使用
ng-template
,因为_4606229_在v4中已弃用 .可能如果您查看浏览器的控制台,您会看到如下错误:
要解决此问题,您必须使用
formGroupName
包装category
:并为
products
:如果
component
文件中的所有内容都正确,它应该可以正常工作 .