5

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)
    }));
  });

2 Answers 2

12

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)
  }
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much @Ricardo, I think that this.fb.array([]) will create an array with one element and not empty one (Zero length).
0

you can write it this way:

let criterias !: FormArray;

and then push the FormGroup ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.