FormArray 对象上的 patchValue?

patchValue on a FormArray object?

我有一系列语言供用户选择 select 和一种默认语言。当默认语言被 selected 时,我想确保该语言的复选框也以编程方式被 selected。

我不确定如何在语言的 FormArray 上使用 patchValue。

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>

先获取语言formArray,然后在匹配的控件上使用patchValue

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

Stackblitz demo

您不需要使用 FormArray 来显示所选语言或使用复杂的 formGroup 来存储简单的值。如果您有唯一变量,请使用 FormControl

defaultLanguage:FormControl=new FormControl('')

//and the .html

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

如果你想显示是否在列表中选中,只需使用 defaultLanguage.value,有些像 (*)

<div *ngFor="let language of languages; index as i">
    <mat-checkbox [checked]="language==defaultLanguage.value"
                  (change)="defaultLanguage.setValue($event.checked?language:null)">
        {{ language }}
    </mat-checkbox>
</div>

(*) 如果你想更改默认语言检查一些复选框,我写代码,如果你只想显示即使它是必要的输入,只是一个

<div *ngFor="let language of languages; index as i">
       {{language==defaultLanguage.value?'ok':''}}{{ language }}
</div>

stackblitz