当我需要<input>
代码中<tr>
标记内的<tr>
代码时,当我生成*ngFor
代码时,我对如何使用Angular 2感到困惑。一个<tr>
。我的情况是这样的:我有一系列&#34;产品&#34;,我应该在input
标签上显示产品信息,并为每个产品显示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);
});
}
}
字段到增加每种产品的库存。这就是我所做的:
<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>
ngOnInit() {
this.formInit();
this.getProducts();
}
formInit(product?: Product) {
this.form = this.formBuilder.group({
products: this.formBuilder.array([])
});
}
在纯html上,我能够取消命名数组,但是使用Angular 2我尝试使用反应形式,但是我应该使用for循环在循环后填充表单以生成每个产品的表格,这听起来像是用很多资源来做一件简单的事情。
使用反应方式
进行更新ProductStokeComponent.ts
<tbody formArrayName="products">
ProductStokeComponent.html
proc sql;
create table lab as
select distinct a.id, sum(case when b.value="New York" then 1 else 0 end)
from latlon a, latlon b
where a.id <> b.id
and geodist(a.lat,a.lon,b.lat,b.lon,"M") <= 50
and a.state = b.state;
答案 0 :(得分:0)
反应性解决方案如下所示:
<tr *ngFor="let product of form.controls['products'].controls">
<td>{{ product.value.id }}</td>
<td>{{ product.value.name }}</td>
<td>{{ product.value.stock }}</td>
<td>
<input #moreStock>
<button (click)="addMoreStock(product.value, moreStock.value)">+</button>
</td>
</tr>
或者,如果您需要模板表单解决方案:
<tbody>
<tr *ngFor="let product of products">
<td>{{ product.id }}</td>
<td>{{ product.name }}</td>
<td>{{ product.stock }}</td>
<td>
<input #moreStock>
<button (click)="addMoreStock(product, moreStock.value)">+</button>
</td>
</tr>
</tbody>
在这两种情况下,在TypeScript文件中添加如下方法:
public addMoreStock(product, howMuch)
{
product.stock += parseInt(howMuch, 10);
}