gpt4 book ai didi

javascript - "Deselect all checkboxes"不适用于 Angular 属性绑定(bind)

转载 作者:行者123 更新时间:2023-11-30 11:30:07 25 4
gpt4 key购买 nike

我已经在 Angular 中使用属性绑定(bind)来取消选择所有复选框,但它没有按预期工作。我的预期:当我单击“清除”按钮时选择一个或多个复选框后,它应该取消选择所有复选框。这是我的 plunker

isSelected is the boolean variable which i have used to set the 'checked' attribute of checkbox. 

模板:

<div *ngFor="let item of items">
<input [checked]="isSelected" type="checkbox">{{item}}
</div>
<button (click)="onClear()">Clear All</button>

组件

private items = ['a', 'b', 'c', 'd'];
private isSelected = false;
constructor() {
}

onClear(){
this.isSelected = false;
}

最佳答案

在您的复选框上设置 ngModel 并使用 ngModelChange 跟踪更改。还设置一个辅助数组来帮助您跟踪选中的状态。这是一个(简化的)示例:

HTML

<input [ngModel]="isSelected[i]" (ngModelChange)="onChange(i)" type="checkbox">{{item}}

typescript

 isSelected =  [];
constructor() {
this.onClear();
}

onChange(i){
this.isSelected[i]=!this.isSelected[i]
}
onClear(){
this.isSelected = [false, false, false, false];
}

DEMO

关于javascript - "Deselect all checkboxes"不适用于 Angular 属性绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46568202/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com