【问题标题】:After Patching Select Value From Dropdown修补后从下拉列表中选择值
【发布时间】:2018-01-24 04:52:20
【问题描述】:

我有这份成分列表,其中包含特定的计量单位。但是,每种成分都有两个计量单位。 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
    });
  }

【问题讨论】:

    标签: angular angular-reactive-forms angular4-forms


    【解决方案1】:

    如果我们有一个表单,其中一些字段取决于对象的值,那么控件的值是自己的对象,而不仅仅是对象的“id”,这很有用 因此,您可以拥有一个带有成分数据的 fbgroup,而不是带有“id”。好吧,当您将数据发送到服务时,不发送成分数据,只发送“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>
    

    在 un submit 中,我们必须像“映射”这样的响应

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

    【讨论】:

    • 你能检查一下这个更新的代码stackblitz.com/edit/form-array-patch-mtiiee?file=app/…。为什么换成分后UOM不变?
    • 谢谢@Eliseo。那么我怎样才能得到component_id以便unit_price可以被补丁呢?这是更新的链接stackblitz.com/edit/form-array-patch-mtiiee?file=app/…
    • 我想你可以写成 ,但是看起来它不属于FormGroup,并且在Measue的不同单位中单价是相同的。那是没有意义的。价格必须是计量单位的属性
    • 好的。由于您使用 [ngValue]="ingredient",我只需要有关如何获取成分 ID 的帮助。如何提取它?
    • console.log 中的结果是 composition_id : "2: Object"。我将如何提取它的 ID?
    猜你喜欢
    • 1970-01-01
    • 2020-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多