0

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: [''],
    });
  }
R. Richards
  • 24,603
  • 10
  • 64
  • 64

1 Answers1

0

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([]),
    });
Joosep Parts
  • 5,372
  • 2
  • 8
  • 33
  • hi! thank u so much for the answer, it worked for me! can i ask you one more question? what doesnt patchvalue work with mat-select? –  Mar 09 '22 at 21:12
  • Wdym? I it works, your values are patched - i.e they are present in template. I am not sure by what you mean "doesnt work". If you mean why none are selected by default you would need give the select and the option `[value]` to indicate which one is selected by default. https://stackoverflow.com/a/51009574/15439733 – Joosep Parts Mar 10 '22 at 03:41