我创建了一个反应式表单,通过单击“添加项目”将在视图中为FromArray元素添加更多行。 我一直在尝试从组件页面手动更新数组元素。我但是我无法从组件更新特定元素或整个元素的数据。我必须更新数组中的数量。我怎样才能做到这一点。
这是我的html代码:
<div class="row" formArrayName="products" *ngFor="let product of this.myForm.get('products').controls; let i=index">
<div class="row" [formGroupName]="i">
<div class="col-md-2">
<select class="custom-select" id="{{'category'+i}}" formControlName="category" (change)="selectCategory($event, i)">
<option value="0" selected>Select a category</option>
<option *ngFor="let c of categoryList" [ngValue]="c.categoryName">{{c.categoryName}}
</option>
</select>
</div>
<div class="col-md-2">
<select class="custom-select" id="{{'productName'+i}}" formControlName="productName" (change)="selectProduct($event, i)">
<option value="0" selected>Select a Product</option>
</select>
</div>
<div class="col-md-2">
<input matInput placeholder="Quantity" id="{{'quantity'+i}}" formControlName="quantity">
</div>
<div class="col-md-2">
<input matInput placeholder="Price Per Unit" id="{{'pricePerUnit'+i}}" formControlName="pricePerUnit">
</div>
<div class="col-md-2">
<input matInput placeholder="Total" id="{{'total'+i}}" formControlName="total">
</div>
</div>
</div>
这是我的组件页面的代码。
ngOnInit() {
this.myForm = this.fb.group({
folio: ['', Validators.required],
paymentType: ['',Validators.required],
products: this.fb.array([
this.addProductFromGroup()
])
});
}
addProductFromGroup(): FormGroup{
return this.fb.group({
category: [''],
productName: [''],
quantity: [''],
pricePerUnit: [''],
total: [''],
})
}
addProduct(){
(<FormArray>this.myForm.get('products')).push(this.addProductFromGroup());
}