我有这个具有特定测量单位的成分列表。但是,每种成分都有两个测量单位。 first_unit和second_unit。如何在修补值后或在选择成分后转移它?如何根据其成分过滤掉测量单位下拉菜单?这里;是我的stackblitz链接
https://stackblitz.com/edit/form-array-patch-mtiiee?file=app/app.component.ts
patchValues(id,i) {
let x = (<FormArray>this.addForm.controls['rows']).at(i);
console.log(x);
x.patchValue({
unit_price: this.ingredients[id - 1].price,
uom: this.ingredients[id - 1].first_unit.name,
// uom: this.ingredients[id - 1].second_unit.name
});
}
答案 0 :(得分:1)
如果我们有一个表单,某些字段取决于对象的值,那么控件的值是自己的对象是有用的,不仅仅是&#34; id&#34;对象 所以,你可以有一个带有ingredientData的fbgroup,而不是&#34; id&#34;。那么,当您将数据发送到服务时,不发送ingredientData,只有&#34; id&#34;
initGroup() {
let rows = this.addForm.get('rows') as FormArray;
rows.push(this.fb.group({
ingredientData: ['', Validators.required], //<--see that not is ingredient_id
unit_price: new FormControl({ value: '', disabled: true }, Validators.required),
uom: ['', Validators.required],
}))
}
然后你的表格就像
<select class="form-control" formControlName="ingredientData">
<option value="null" hidden>-- Select Ingredient --</option>
<option *ngFor="let ingredient of ingredients" [ngValue]="ingredient">{{ingredient.name}}</option>
</select>
<select class="form-control" formControlName="uom">
<option value="null" hidden>-- Select Unit of Measure --</option>
<option *ngIf="row.value.ingredientData" [value]="row.value.ingredientData.first_unit.id">
{{row.value.ingredientData.first_unit.name}}
</option>
<option *ngIf="row.value.ingredientData" [value]="row.value.ingredientData.second_unit.id">
{{row.value.ingredientData.second_unit.name}}
</option>
</select>
未提交,我们必须&#34; mappear&#34;像
这样的回应onSubmit(){
const data = {
ingredient: this.addForm.get('rows').value.map((x)=>{
//from each row, we create a new object
return {
id:x.ingredientData.id,
unit_price:x.ingredientData.price,
uom:x.uom
}
})
}