menu

Questions & Answers

How to create empty formarray

I would like to create an empty formarray so i will be able to push elements later.

i know that i can do something like this using "criterias.controls.length = 0;" after declaring the FormArray but i'm looking for a way to create the formArray with 0 length in the as part of the declaration.

criterias = new FormArray([]);
criterias.controls.length = 0;
values.forEach(item => {
    criterias.controls.push(new FormGroup({
      'type': new FormControl(item.type, Validators.required),
      'criteria': new FormControl(item.criteria, Validators.required)
    }));
  });
Answers(2) :

you can use the form builder class to help you create the reactive form

    this.baseForm = this.fb.group({
        criterias: this.fb.array([])
    })

also is good if you have a method that returns you form array

get criterias(): FormArray {
    return this.baseForm.get("criterias") as FormArray
}

base on that you can create a add method an a remove method

  addCriteria() {
    this.criterias.push(this.fb.group({

     }))
  }

  removeCriteria(index) {
      this.criterias.removeAt(index)
  }
Comments:
2023-01-23 19:42:02
Thank you very much @Ricardo, I think that this.fb.array([]) will create an array with one element and not empty one (Zero length).

you can write it this way:

let criterias !: FormArray;

and then push the FormGroup ...