【发布时间】:2017-09-24 08:55:09
【问题描述】:
当我需要表格的<tr> 标签内的<input> 标签,而<tr> 标签是由*ngFor 生成时,我对如何使用Angular 2 有点困惑。我的情况是这样的:我有一系列“产品”,我应该在<tr> 标签上显示产品信息,并且对于每个产品,一个input 字段以增加每个产品的库存。这就是我所做的:
ProductStokeComponent.ts
export class ProductStokeComponent implements OnInit {
form: FormGroup;
products: Subject<Product[]> = new Subject();
constructor(
private productService: ProductService,
private formBuilder: FormBuilder,
) { }
ngOnInit() {
this.formInit();
this.getProducts();
}
formInit() {
this.form = this.formBuilder.group({
products: this.formBuilder.array([])
});
}
getProducts() {
this.productService.getProducts().subscribe(data => {
this.products.next(data);
});
}
}
ProductStokeComponent.html
<form [formGroup]="form" (ngSubmit)="formSubmit()">
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Stock</th>
<th>Stock Entrance</th>
</tr>
</thead>
<tbody formArrayName="products">
<tr *ngFor="let product of products| async">
<td>{{ product.id }}</td>
<td>{{ product.name }}</td>
<td>{{ product.stock }}</td>
<td>
<input type="number" name="stock[product.id]" >
</td>
</tr>
</tbody>
</table>
<button type="submit">Add Stock</button>
</form>
在纯 html 上,我能够取消命名数组,但在 Angular 2 中,我尝试使用反应式表单,但随后我应该使用 for 循环在循环后填充表单以生成表格对于每个产品来说,这听起来像是使用大量资源来做一件简单的事情。
使用反应形式的方法更新
ProductStokeComponent.ts
ngOnInit() {
this.formInit();
this.getProducts();
}
formInit(product?: Product) {
this.form = this.formBuilder.group({
products: this.formBuilder.array([])
});
}
ProductStokeComponent.html
<tbody formArrayName="products">
【问题讨论】:
-
想法是在
input中放入要添加到库存中的元素数量? -
是的,应该是输入数字
标签: angular typescript angular2-forms