我将formArray用于产品列表。我想像[ngModel]一样在.ts中获取product_code
的值,然后处理数据。如何获得product_code
的值?
<tbody formArrayName="products">
<tr *ngFor="let phone of productForms.controls; let i=index" [formGroupName]="i">
<th scope="row">{{i+1}}</th>
<td><input type="text" class="form-control" placeholder="Product Code" formControlName="product_code"></td>
<td><input type="text" class="form-control" placeholder="Product Name" formControlName="product_name"></td>
<td><button type="button" class="btn btn-danger ml-2" (click)="deleteProduct(i)">Remove</button></td>
</tr>
</tbody>
.ts代码:
ngOnInit() {
const product = this.fb.group({
product_code: [],
product_name: [],
product_price: [],
product_quantity: [1],
product_total: []
});
this.myForm = this.fb.group({
products: this.fb.array([product]),
}
}
get productForms() {
return this.myForm.get('products') as FormArray;
}
addProduct() {
const product = this.fb.group({
product_code: [],
product_name: [],
product_price: [],
product_quantity: [1],
product_total: []
});
this.productForms.push(product);
}
deleteProduct(i) {
this.productForms.removeAt(i);
}
当我在product_code
字段中输入任何数字时,我需要.ts代码中的该值,该值也可以处理更改或说预订。
我想获取product_code
的值,执行一些功能并将返回值分配给product_name
。我知道如何使用ngModel两种方式实现此目标,但是如何使用FormControl或说Reactiveforms?
答案 0 :(得分:1)
这里有一个示例,您可以如何遍历products
并获取例如。 product_quantity
值:
const product = this.fb.group({
product_code: [],
product_name: [],
product_price: [],
product_quantity: [1],
product_total: []
});
const form = this.fb.group({
products: this.fb.array([product]),
});
const productsArray = form.controls.products as FormArray;
const productsNumber = productsArray.controls.length;
for (let i = 0; i < productsNumber; i++) {
const productGroup = productsArray.controls[i] as FormGroup;
console.log(productGroup.controls.product_quantity.value);
}
@编辑1 上面的样本只有在您要求的时候才会获得价值。
这里是要随时更改它:
for (let i = 0; i < productsNumber; i++) {
const productGroup = productsArray.controls[i] as FormGroup;
productGroup.controls.product_code.valueChanges.subscribe(val => {
// Whenever value of product code changes update product name
productGroup.controls.product_name.setValue(val + 'some value');
});
}
@Edit 2修改的addProduct
方法以对新添加的控件做出反应:
addProduct() {
const product = this.fb.group({
product_code: [],
product_name: [],
product_price: [],
product_quantity: [1],
product_total: []
});
product.controls.product_code.valueChanges.subscribe(val => {
// Whenever value of product code changes update product name
product.controls.product_name.setValue(val + 'some value');
});
this.productForms.push(product);
}