Home > front end >  angular patchValue json data with reactive forms
angular patchValue json data with reactive forms

Time:03-10

I am doing edit page and I am trying to set my forms default value with data I got from API.

My issue is that I have two items in my array but it creates another empty formArray;

What am I doing wrong?

here is my 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: [''],
    });
  }

CodePudding user response:

Very difficult to understand what you're trying to do here, fyi. But your described problem comes from this.initCat().

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

Remove it to remove the empty extra form.

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