Angular ngModel选中所有复选框 [英] Angular ngModel checks all checkboxes
问题描述
尝试使用ngModel选中/取消选中所有子复选框,并选中所有复选框,但也尝试单独检查子项,并始终选中所有复选框;
Trying to check/uncheck all children checkboxes using ngModel and all checkboxes are checked, but also trying to check alone children and all checkboxes are always checked;
<div>
<input type="checkbox" [checked]="myVar1" (change)="myVar1 = !myVar1" /> Parent
</div>
<ul>
<input type="checkbox" [(ngModel)]="myVar1" /> Child1<br>
<input type="checkbox" [(ngModel)]="myVar1" /> Child2
</ul>
尝试使用[ngModelOptions] ="{standalone:true}"属性,其结果具有相同的行为-选中了所有复选框;
Tried using [ngModelOptions]="{standalone: true}" property and it results with the same behaviour - all checkboxes are checked;
<div>
<input type="checkbox" [checked]="myVar2" (change)="myVar2 = !myVar2" /> Parent
</div>
<ul>
<input type="checkbox" [(ngModel)]="myVar2" [ngModelOptions]="{standalone: true}" /> Child1<br>
<input type="checkbox" [(ngModel)]="myVar2" [ngModelOptions]="{standalone: true}" /> Child2
</ul>
如何使每个子复选框都独立? stackblitz
How to make every child checkbox standalone? stackblitz
推荐答案
您正在对子代和父代使用相同的 [(ngModel)]
,这使得一旦检查了父代就对子代进行了检查.
You are using the same [(ngModel)]
for child and parent which makes the child checked as soon as parent is checked.
您需要为孩子使用不同的 [(ngModel)]
,并在父复选框上使用选中/更改的功能来检查所有孩子,即将孩子 ngModel
设置为 true
或 false
.
You need to have different [(ngModel)]
for children and use a checked/changed function on parent checkbox to do the check all child i.e set child ngModel
to true
or false
.
EX:
<div>
<input type="checkbox" [checked]="myVar1" (change)="updateChildSelection($event)" /> Parent
</div>
<ul>
<input type="checkbox" [(ngModel)]="myVarChild1" /> Child1<br>
<input type="checkbox" [(ngModel)]="myVarChild2" /> Child2
</ul>
在组件中:
updateChildSelection(event) {
// set child to true if checked
if(event.target.checked){
this.myVarChild1 = true;
this.myVarChild2 = true
} else {
//set child model to false
}
}
这篇关于Angular ngModel选中所有复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!