Search code examples
angularangular-reactive-formsangular-formbuilder

Create a FormBuilder array with number of controls expressed by another input


I'm writing an Angular 5 app at the moment where I need to use a FormBuilder array for one of the properties. I have one property which states how many controls should be in the array but can't find any resources on how to create a FormBuilder array with that many controls.

The form looks something like this:

this.Form = this.fb.group({
    ...
    noOfControls: null, // 
    controls: <-- fb.array
});

What would be the best way to go about doing this?


Solution

  • you should create a observable that listen the to the noOfControls values, inside this observable you should call a method that add or remove controls to your formArray based on the length of your current control

    let say this is your form

    this.Form = this.fb.group({
        noOfControls: this.fb.control(null,[]),
        controls: this.fb.array([])
    });
    

    to listen the changes of your control you can use

    this.Form.valueChanges.map(values=>values.noOfControls).distinctUntilChanged()
    .subscribe((num)=>{
         ...
        })
    

    to handle in a easy way your controls inside the array you can create a method that return the control as array

    get control() {
     return this.form.get('controls') as FormArray
    }
    

    inside the subscription you should have some kind of logic that analyze every time that the number change the length of your control array

    if(this.control.length > num) {
     ... remove one control array item
    }
    if(this.control.length < num) {
     ... add the differences in the number of control items
    }
    

    to remove the last element you can use the removeAt(index: number) method from the FormArray class

    to add a new form control you can use push(control: AbstractControl)

    let me know if you need more help