【问题标题】:Retrieving Item Information in FormArray in Reactive Forms在响应式表单中检索 FormArray 中的项目信息
【发布时间】:2019-01-25 21:00:02
【问题描述】:

我需要一些帮助才能通过在下拉菜单中选择成分名称来获取单价。所以我所做的是从 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
        });
      }

【问题讨论】:

  • 更新数据库是什么意思??请解释一下你的目标??
  • @UnluckyAj。很抱歉让您感到困惑。简而言之,除了这个patchValues()函数,还有其他方法可以获取单价吗?

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


【解决方案1】:

您可以通过下面的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
    });
  }

【讨论】:

  • 谢谢。顺便说一句,find(x => x.id == id); 中有错误。 x 有这个错误 "[tslint] Shadowed name: 'x' (no-shadowed-variable"
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-11
  • 1970-01-01
  • 1970-01-01
  • 2019-10-14
  • 1970-01-01
  • 2020-03-03
  • 1970-01-01
相关资源
最近更新 更多