Johnathan Tran
Johnathan Tran

Reputation: 63

How to set values in formarray

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?

Upvotes: 5

Views: 23720

Answers (3)

Abdullah
Abdullah

Reputation: 2973

Below solution Works for me:

(this.bookAppointment.get('serviceTypeArray') as FormArray).controls.forEach(c => {
      c.setValue(false)
 });

In Detail:

    bookAppointment: FormGroup;

    constructor(
        private _fb: FormBuilder,
    )

    this.bookAppointment = await this._fb.group({
        userId: [this._gService.USER_ID, Validators.required],
        serviceTypeArray: this._fb.array(this.serviceTypeCloneArray.map(x => false)),
    });


    resetServiceType(){
        (this.bookAppointment.get('serviceTypeArray') as FormArray).controls.forEach(c => {
          c.setValue(false)
        });
    }

Upvotes: 1

Livia Lima
Livia Lima

Reputation: 101

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

Upvotes: 10

Caio Oliveira
Caio Oliveira

Reputation: 844

Your code seems to be working fine.

I just did a stackblitz and it worked.

Make sure you are setting the values after the formArray was pushed.

https://stackblitz.com/edit/angular-jstjzc?file=src/app/app.component.ts

Upvotes: 0

Related Questions