5

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?

3 Answers 3

10

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

Sign up to request clarification or add additional context in comments.

1 Comment

this solution also works stackoverflow.com/a/42599327/9033834
1

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

Comments

0

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

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.