修补 Select 下拉列表中的值后

After Patching Select Value From Dropdown

我有这份成分清单,上面有特定的计量单位。但是,每种成分都有两个计量单位。 first_unit 和 second_unit。我如何在修补价值或选择成分后转移它?我如何根据其成分过滤掉测量单位下拉列表?这是我的 stackblitz link

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
    });
  }

如果我们有一个表单,其中某些字段取决于对象的值,那么控件的值是自己的对象是很有用的,而不仅仅是对象的 "id" 因此,您可以使用 ingredientData 而不是 "id" 创建一个 fbgroup。那么,当您将数据发送到服务时,不发送 ingredientData,只发送 "id"

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>

在取消提交时,我们必须"mappear"回复

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
        }
      })
    }