angular patchValue json 具有反应形式的数据

angular patchValue json data with reactive forms

我正在编辑页面,我正在尝试使用从 API.

获得的数据设置我的表单默认值

我的问题是我的数组中有两个项目,但它创建了另一个空的 formArray;

我做错了什么?

这是我的 stackblitz

  this.filterForm = this.fb.group({
      categories: this.fb.array([this.initCat()]),
    });

    const control = <FormArray>this.filterForm.get('categories');
    console.log(control);
    this.chosenCarPartCategories.carPartCategories.forEach((x) => {
      control.push(
        this.patchValues(x.name, x.carPartSubCategoryId, x.quantity, x.comment)
      );
    });

  patchValues(name, carPartSubCategoryId, quantity, comment) {
    return this.fb.group({
      carPartCategory: [name],
      carPartSubCategory: [carPartSubCategoryId],
      quantity: [quantity],
      comment: [comment],
    });
  }

  initCat() {
    return this.fb.group({
      carPartCategory: ['', Validators.required],
      carPartSubCategory: ['', Validators.required],
      quantity: ['', Validators.required],
      comment: [''],
    });
  }

很难理解你在这里想做什么,仅供参考。但是你描述的问题来自this.initCat().

    this.filterForm = this.fb.group({
      categories: this.fb.array([this.initCat()]),
    });

删除它以删除空的额外表格。

    this.filterForm = this.fb.group({
      categories: this.fb.array([]),
    });