当您将 mat-checkbox 与 FormControl 一起使用时,您不应该使用选中(如果您使用模板驱动表单,则等于。您应该通过 formControl 管理值) 例如
subtasks: [
{name: 'Primary', completed: false},
{name: 'Accent', completed: false},
{name: 'Warn', completed: false},
],
form=new FormGroup({
Primary:new FormControl(false),
Accent:new FormControl(false),
Warn:new FormControl(false),
})
并使用:
<ul [formGroup]="form">
@for (subtask of task.subtasks; track subtask) {
<li>
<mat-checkbox [formControlName]="subtask.name">
{{subtask.name}}
</mat-checkbox>
</li>
}
</ul>
另一种方法是使用检查的属性和事件更改的方式
<ul>
@for (subtask of task.subtasks; track subtask) {
<li>
<mat-checkbox [checked]="form.get(subtask.name)?.value"
(change)="form.get(subtask.name)?.setValue($event.checked)">
{{subtask.name}}
</mat-checkbox>
</li>
}
</ul>
astackblitz
就像 Angular 中使用反应形式的示例一样。看到 stackblitz 中有两个函数和一个变量 allComplete
allComplete: boolean = false;
someComplete(): boolean {
return Object.keys(this.form.controls)
.filter(key => this.form.get(key)?.value).length > 0 &&
!this.allComplete;
}
updateAllComplete() {
this.allComplete = Object.keys(this.form.controls)
.filter(key => !this.form.get(key)?.value).length==0
}
//in setAll
setAll(completed: boolean) {
this.allComplete=completed //<--we add this line also
this.subtasks.forEach(t => this.form.get(t.name)?.setValue(completed));
}
管理典型的“selectAll”