如何在角度2中存储复选框的已选中或未选中事件

时间:2017-03-24 07:20:30

标签: javascript jquery angularjs angular checkbox

<form (submit)="onSubmit()">
  <div class="container">
      <div *ngFor="let initial of initialState,let j = index" >
          <div *ngIf="initial>0">


              <button class="button" type="button">Device {{j}}</button>
              &nbsp; 
              <label class="switch">
                  <input type="checkbox"  id="checkbox_category" checked (change)="search(initial, $event)" />
                  <div class="slider round"></div>
              </label>
          <br/> 
          </div>

          <div *ngIf="initial===0">
              <button class="button" type="button">Device {{j}}</button>
              &nbsp; 
              <label class="switch">
                  <input type="checkbox"  id="checkbox_category" (change)="search(initial, $event)" />
                  <div class="slider round"></div>
              </label>
          <br/> 
          </div>
      </div>
  </div>
  <button class="button" type="button">Submit</button>
 </form>

export class DashboardComponent{

  initialState:any = [1,1,1,0,0,0,1];
  intendedDeviceStatus: any = this.initialState;

  search(category:any, event:any) {

        var index = this.initialState.indexOf(category);
        this.intendedDeviceStatus[index]= (~this.intendedDeviceStatus[index]);      

}

在上面的代码中,我有一个Initailstatus数组,它在显示复选框后根据显示的checkboxes进行检查和取消选中。在我更改选中复选框后显示它以取消选中它未在IntendedDevicesArray中更新。

1 个答案:

答案 0 :(得分:0)

因为initialState是数字而不是对象的数组。所以方法array.indexOf(value)找到第一个等于该值的元素。因此,它返回错误的索引;

示例:

var a = [1,1,1,0, 0 ,0,1];
var b = a[2];
var c = a.indexOf(b); c = 0 not 2

使代码正常工作 从中改变 <input ... (change)="search(initial, $event)" />
 到
<input ... (change)="search(j, $event)" />

并更改搜索功能:

search(index:number, event:any) {
    this.intendedDeviceStatus[index]= this.intendedDeviceStatus[index] ? 1 : 0;      

}

除此之外,我建议你使用initialState作为数字的布尔数组 user * ngIf =&#34; initial&#34; for checked and * ngIf =&#34;!initial&#34;未经检查。在搜索功能

this.intendedDeviceStatus[index] = !this.intendedDeviceStatus[index];

如果您希望代码更简短,您可以编写支持输入标记双向绑定的指令。