将元素推送到反应形式数组会导致ExpressionChangedAfterItHaHasBeenCheckedError

时间:2018-12-13 22:44:22

标签: angular angular-reactive-forms

事实证明,我对现代Angular框架有一个非常普遍的问题,而我无法通过查看其他问题来解决。

我有一个使用反应形式的形式,该形式具有动态部分。当我单击按钮以将新项目添加到动态部件时,它将引发ExpressionChangedAfterItHaHasBeenCheckedError,

  

错误错误:ExpressionChangedAfterItHasBeenCheckedError:检查表达式后,表达式已更改。先前的值:“已禁用:false”。当前值:“已禁用:true”。

我知道问题出在生命周期中,但是我无法解决这个问题。

这是我的表单并添加功能

    public wishlistForm = this.fb.group({
    name: [""],
    creator: [""],
    category: [WishlistCategories.GENERAL],
    description: [""],
    countryCode: [""],
    isForMarketingPurpose: [false],
    password: [{ value: "", disabled: false }],
    products: this.fb.array([this.fb.group(ReactiveWishModel)])
  });

  get products() {
    const products = this.wishlistForm.get("products") as FormArray;
    return products.controls;
  }

  constructor(
    private wishlistService: WishlistsService,
    private router: Router,
    private domSanitizer: DomSanitizer,
    public headerService: HeaderService,
    private fb: FormBuilder
  ) {}

  ngOnInit() {
    if (this.typeOfAction === UPDATE_ACTION_TYPE) {
      this.wishlistForm.get("password").disable();
    }
    this.wishlistForm.patchValue(this.wishlist);

    const products = this.wishlistForm.get("products") as FormArray;
    products.removeAt(0);
    this.wishlist.products.forEach(product =>
      products.push(this.fb.group(ReactiveWishModelFactory(product)))
    );

    this.wishlistForm.statusChanges.subscribe(status => {
      const isDisabled = status === "INVALID" ? true : false;
      this.headerService.setIsButtonDisabled(isDisabled);
    });
  }
  addWish() {
    (this.wishlistForm.get("products") as FormArray).push(
      this.fb.group(ReactiveWishModel)
    );
  }

任何建议如何避免这种情况?

0 个答案:

没有答案