How to set values in formarray

Viewed 6972

I have a form array that is dynamically set after getting data from a service with initial values being false.

constructor(){
    this.form = this.fb.group({
        //...other controls...
        addOns: fb.array([])
    })
}
ngOnInit(){
    this.addonsService.getAll()
    .subscribe(result =>  {
      this.addOns = result;
      for(let addOn in this.addOns) {
        this.form.get('addOns').push(new FormControl(false));
      }
    });
}

I need to then set the values in the array based on another set of values. I have tried

var formArray = this.form.get('addOns') as FormArray;

Then looping through, but this doesn't work

formArray.controls.forEach(c => {
    c.setValue(true)
})

I also tried calling by index, but this returns undefined

formArray.controls[0].setValue(true);

If I console.log() formArray I get the expected number of form controls.

How can I set the values of the formArray after dynamically building it?

2 Answers

If you want to set only one specific item of your formArray, you'll need the index of the item you want to modify, than you can do:

formArray.at(index).setValue()
formArray.at(index).get('controlName').setValue()

https://angular.io/api/forms/FormArray#at

Related