在响应式表单中检索 FormArray 中的项目信息

Retrieving Item Information in FormArray in Reactive Forms

我需要一些帮助来获取单价,方法是在下拉列表中选择成分名称。所以我所做的是从 formArray 中获取索引。我还得到了成分 ID 并将其减去 1,然后放入成分索引以匹配 formArray 中的索引。但是还有别的办法吗?因为如果将来我的数据库中有一些变化,比如当我从数据库中删除一种成分时,那么 id 将被跳过。请在下面查看我的代码。

这也是我的 stackblitz link。 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
        });
      }

您可以通过 id 查找成分,如下所示 selectedIngredient

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