我有一个角度2反应形式,其中包含一组数据绑定的复选框。这工作正常,但现在我需要添加一个按钮来检查所有复选框。
以下是我的FormGroup配置方式:
private buildForm() {
this.groupForm = this._formBuilder.group({
bookId: this._formBuilder.control(null),
startDate: this._formBuilder.control(null),
groupTotal: this._formBuilder.control(null),
chapterGrouping: this._formBuilder.control("all"),
groupChapters: this.buildChapters()
});
}
private buildChapters() {
const chapters = this.chapters.map(chapter => {
return this._formBuilder.control(chapter.selected)
});
return this._formBuilder.array(chapters);
}
继承我的HTML:
<div class="form-group">
<label for="">Select chapters</label>
<div *ngFor="let chapter of formChapters.controls; let i=index" class="checkbox">
<label>
<input type="checkbox" [formControl]="chapter" >
{{chapters[i].title}}
</label>
</div>
</div>
如何访问FormArray以将所有复选框设置为已选中?
答案 0 :(得分:5)
您的模板将如下所示:
<div class="form-group" formGroupName="groupChapters">
<label for="">Select chapters</label>
<div *ngFor="let chapter of formChapters.controls; let i = index" class="checkbox">
<label>
<input type="checkbox" formControlName="{{i}}">
{{chapters[i].title}}
</label>
</div>
<button (click)="checkAll()">Check all</button>
</div>
您添加到班级的方法:
private checkAll() {
this.groupForm.controls['groupChapters'].setValue(
this.groupForm.controls['groupChapters'].value
.map(value => true);
);
}
正在工作的Plunk:http://embed.plnkr.co/8yXBn1DhboiIwRIv7AS0/