Angular 4 - 取消选中时从数组中删除值复选框

时间:2017-10-26 02:42:26

标签: angular typescript

取消选中复选框时,如何从数组中删除值?

HTML

<input type="checkbox" id="saveUserNameCheckBox" (change)="selChk(member.id)"  [checked]="false">

组件

selChk(val) {

   if (this.id.indexOf(val) == -1) {
    this.id.push(val);
    console.log(this.id);
   }
}

2 个答案:

答案 0 :(得分:6)

您已找到索引,为什么不只使用splice

selChk(val) {
 var index = this.id.indexOf(val);
 if(index === -1){
   // val not found, pushing onto array
   this.id.push(val);
 }else{
   // val is found, removing from array
   this.id.splice(index,1);
 }
}

答案 1 :(得分:1)

您的HTML:

<input (change)="onCheckUser(user.user_id,$event)" type="checkbox">

在您的Ts中:

Follow_list = []; // Variable Declared 


onCheckUser(Id, event) {
  const checked = event.target.checked; // stored checked value true or false
   if (checked) {
     this.Follow_list.push({ user_id: Id }); // push the Id in array if checked
      } else {
      const index = this.Follow_list.findIndex(list => list.user_id == Id);//Find the index of stored id
      this.Follow_list.splice(index, 1); // Then remove
    }
 }