我想问一下,尽管 opt.checked 为 true,但这些多个复选框未与 [checked] 双向绑定绑定有什么问题

问题描述 投票:0回答:1
angular checkbox angular-material
1个回答
0
投票

当您将 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>

a 
stackblitz

就像 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”

© www.soinside.com 2019 - 2024. All rights reserved.