简体   繁体   English

“取消选中所有复选框”不使用角度属性绑定

[英]“Deselect all checkboxes” not working with angular property binding

I have used property binding in angular to deselect all checkboxes, but it is not working as expected. 我在angular中使用了属性绑定来取消选中所有复选框,但它没有按预期工作。 What i expected: After selecting one or more checkboxes when i click 'clear' button it should deselect all checkboxes. 我的期望:当我点击“清除”按钮选择一个或多个复选框后,它应该取消选中所有复选框。 here is my plunker 这是我的傻瓜

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

template: 模板:

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

Component 零件

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

  onClear(){
    this.isSelected = false;
  }

Set ngModel on your checkboxes and track the changes with ngModelChange . 在复选框上设置ngModel并使用ngModelChange跟踪更改。 Also Set an auxiliary array to help you track the checked status. 还设置辅助阵列以帮助您跟踪已检查状态。 Here is a (simplified) example: 这是一个(简化)示例:

HTML 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 DEMO

One solution is 一个解决方案是

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

with the template: 使用模板:

private items = [ {'label':'a', 'checked': false },
  {'label':'b', 'checked': false},
  {'label':'c', 'checked': false},
  {'label':'d', 'checked': false}];

onClear(){
    for ( let cb of this.items ) {
      cb.checked = false;
    }
  } 

At first, you should know [checked] not working and you should use [(ngModel)] for this thing and you should import FormModule from @angular/forms. 首先,你应该知道[checked]不工作,你应该使用[(ngModel)]这个东西,你应该从@ angular / forms导入FormModule。

second, you should have multiple isSelected variable because if you use just one isSelected variable when you select one of them, all checkboxes will be select, for that you can use array like this in .ts file, 第二,你应该有多个isSelected变量,因为如果你在选择其中一个时只使用一个isSelected变量,那么所有的复选框都将被选中,因为你可以在.ts文件中使用这样的数组,

items = [{name: 'a', isSelected:false}, 
         {name: 'b', isSelected:false},
         {name: 'c', isSelected:false},
         {name: 'd', isSelected:false}];

and in HTML 并在HTML中

<div *ngFor="let item of items">
    <input [(ngModel)]="item.isSelected" type="checkbox">{{item.name}}
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM