patchValue on a FormArray object?

12,560

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

Share:
12,560
Ryan Loggerythm
Author by

Ryan Loggerythm

10 HOME 20 SWEET 30 GOTO 10

Updated on June 27, 2022

Comments

  • Ryan Loggerythm
    Ryan Loggerythm almost 2 years

    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>
    
    • prabhatojha
      prabhatojha over 4 years
      Could you please create stackblitz working project for this problem.
    • Eliseo
      Eliseo over 4 years
      @Ryan, why you use a FormArray if you really only want to store an unique variable -defaultLanguage-?, check my answer
    • Ryan Loggerythm
      Ryan Loggerythm over 4 years
      Hi @Eliseo, this is a very simplified example of the full code I'm trying to build :)