我有一系列语言供用户选择,并有默认语言可供选择。 选择默认语言时,我想确保也以编程方式选中该语言的复选框。
我不确定如何在语言的FormArray上使用patchValue。
组件.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++;
}
}
组件.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
堆栈闪电战演示
不需要使用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>
查看堆叠闪电战