【问题标题】:Error: Must supply a value for form control with name: <name>错误:必须为表单控件提供一个值,名称为:<name>
【发布时间】:2019-03-09 09:47:19
【问题描述】:

我有一个嵌套操作,以便首先删除报价,然后将其再次保存为重复报价。

问题是,保存重复报价后,我想patchValue()offerList[index]中的项目。这是我得到错误的地方:

错误:必须为表单控件提供一个值,名称为:'id'。

然而,调试显示一切都应该没问题。最终订阅中的对象saved 设置了有效字段。 id 存在且不为空:

this._offerService.remove(this.placeId, offer)
  .pipe(
    flatMap((removed: OfferModel) => {
      // Re-use the removed offer to save a repeating one
      removed.id = null;
      removed.repeatWeekly = true;
      return this._offerService.save(this.placeId, removed)
        .pipe(finalize(() => this.updateOffersFormArray()));
    }),
  )
  .subscribe(
    (saved) => {
      console.log(saved);
      // offerList is either this.offers or this.repeatingOffers
      offerList[index].patchValue(saved);
    });

控制台将记录:

{id: 55, offerDate: "2019-03-04", …}

这就是updateOffersFormArray()中发生的事情:

// this.offersFormArray is a FormArray
updateOffersFormArray() {
  const tmp = this.repeatingOffers.concat(this.offers);
  console.log(tmp);
  this.offersFormArray.setValue(tmp); // <-- Throws error
}

控制台输出向我显示了一个 FormGroup 元素的数组,正如预期的那样,这些 FormGroup 元素中的每个 value 都有一个包含所有值的报价 - 特别是 id - 这是根据未设置错误消息。

我已经为此苦苦思索了很长一段时间,但我只是看不到它。

我知道代码看起来有点奇怪。在updateOffersFormArray() 执行后,this.offersFormArray 的状态更改事件将更新this.offersthis.repeatingOffers,这是我显示所需的。只是为了完成图片,这是执行此操作的代码:

this.offersFormArray.statusChanges.subscribe((e) => {
  const offers: Array<AbstractControl> = [];
  const repeatingOffers: Array<AbstractControl> = [];

  for (const k of Object.keys(this.offersFormArray.controls)) {
    const offerForm = this.offersFormArray.controls[k];
    const offer = <OfferModel> offerForm.value;

    if (offer.repeatWeekly) {
      repeatingOffers.push(offerForm);
    } else {
      offers.push(offerForm);
    }
  }

  this.offers = offers;
  this.repeatingOffers = repeatingOffers;
});

【问题讨论】:

标签: angular typescript


【解决方案1】:

原来我对setValue()FormArray 有误。它不接受AbstractControl 的列表,而是需要与控件结构匹配的值。

我要做的就是改变

this.offersFormArray.setValue(tmp); 

this.offersFormArray.setValue(tmp.map(control => control.value));

【讨论】:

  • 这种方式会在 Angular 11 Cannot find form control at index 1显示错误
猜你喜欢
  • 1970-01-01
  • 2018-04-24
  • 1970-01-01
  • 2018-12-05
  • 1970-01-01
  • 2019-02-12
  • 2019-01-11
  • 2019-05-11
  • 2018-11-02
相关资源
最近更新 更多