如何取消选中mat中最后一个选中的项目复选框

时间:2018-05-21 10:18:46

标签: angular angular-material

我想从mat复选框中取消选中上次检查的项目,请找到以下代码...

<div *ngFor="let item of data; let i = index;">
      <md-checkbox [checked]="item.checked" (change)="onChange($event, i, item)">
        {{item.label}}
 </md-checkbox>

data = [
    { label: 'one', checked: false },
    { label: 'two', checked: false },
    { label: 'three', checked: true },
    { label: 'four', checked: false },
    { label: 'five', checked: false }
    ];

onChange(event, index, item) {

      item.checked = !item.checked;

      this.lastAction = 'index: ' + index + ', label: ' + item.label + ', checked: ' + item.checked;

      console.log(index, event, item);

  }

1 个答案:

答案 0 :(得分:1)

//First find last element of your array than remove like below on change event
data = [

    { label: 'one', checked: false },
    { label: 'two', checked: false },
    { label: 'three', checked: true },
    { label: 'four', checked: false },
    { label: 'five', checked: false }
    ];
var lastfind=data.slice(-1)[0];
var i;
for (i = 0; i < data.length; i++) { 
console.log(lastfind.label);
console.log(data.label);
if(data[i].label==lastfind.label){
console.log('test');
  data.splice(-1,1)
}
}
console.log(data);