【发布时间】:2017-04-27 00:40:46
【问题描述】:
使用 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>
【问题讨论】:
-
嘿,我的回答对你有用吗?
标签: angular templates typescript reactive-forms