Search code examples
angularangular-reactive-formsangular-formsformbuilderformarray

patchValue on a FormArray object?


I have an array of languages for a user to select and a default language to pick. When a default language is selected, I want to make sure the checkbox for that language is also selected programmatically.

I'm not sure how to use patchValue on the FormArray of languages.

component.ts

import { FormGroup, FormControl, FormArray, Validators } from '@angular/forms';
...

constructor(...) {
    this.languages = ['English', 'Spanish', 'Mandarin', 'Klingon'];

    this.myForm = new FormGroup({
        languages: this.createLanguagesControl(),
        defaultLanguage: new FormControl('', Validators.required)
    });
}

createLanguagesControl() {
    const controls = this.languages.map(language => {
        return new FormControl(false);
    });
    return new FormArray(controls);
}

defaultLanguageSelection() {
    let formValues = this.myForm.value;
    console.log('defaultLanguageSelection', formValues.defaultLanguage);

    let i = 0;
    for (let language of this.languages) {
        if (language == formValues.defaultLanguage) {              // find the index of our newly-selected default language in the languages array
            this.myForm.patchValue({languages: {i: true}});        // make sure the language is checked
        }
        i++;
    }
}

component.html

<mat-card-content>

    <div formArrayName="languages" *ngFor="let language of languages; index as i">
        <mat-checkbox formControlName="{{ i }}">
            {{ language }}
        </mat-checkbox>
    </div>

    <mat-form-field>
        <mat-label>Default Language</mat-label>
        <mat-select formControlName="defaultLanguage">
            <mat-option *ngFor="let language of languages" [value]="language" (click)="defaultLanguageSelection()">
                {{ language }}
            </mat-option>
        </mat-select>
    </mat-form-field>

</mat-card-content>

Solution

  • Get language formArray first and then use patchValue on the matching control

    let langArr = <FormArray>this.myForm.controls["languages"];
    langArr.controls[i].patchValue(true);     // i is the matching index
    

    Stackblitz demo