以反应形式在FormArray中检索项目信息

时间:2018-08-19 14:39:18

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

通过在下拉列表中选择成分名称,我需要一些帮助来获取单价。所以我所做的是我从formArray获取索引。我还获取了成分ID,并将其减去1,然后输入成分的索引,以匹配formArray的索引。但是还有其他方法吗?因为如果将来我的数据库中有某些更改(例如当我从数据库中删除成分时),那么该ID将被跳过。请在下面查看我的代码。

这也是我的stackblitz链接。 CLICK THIS LINK FOR STACKBLITZ

    onSelectIngredient(event,i): void {
        this.patchValues(event.target.value,i);
      }

   patchValues(id,i) {
        let x = (<FormArray>this.addForm.controls['rows']).at(i);
        console.log(x);

        x.patchValue({
          unit_price: this.ingredients[id - 1].price
        });
      }

1 个答案:

答案 0 :(得分:1)

您可以通过selectedIngredient下方的ID查找配料。

patchValues(id,i) {
    let x = (<FormArray>this.addForm.controls['rows']).at(i);

    const selectedIngredient = this.ingredients.find(y => y.id == id); // beware of number and string

    x.patchValue({
      unit_price: selectedIngredient.price
    });
  }