首页 > 解决方案 > 如何使用 angular + 从数组中删除列表

问题描述

我正在使用复选框来获取以下列表是数据:

data:[{ email: "email1" }, { email: "email2" }, { email: "email3" }, { email: 'email4' }]

html

<table>
  <thead>
     <th></th>
     <th></th>
   </thead>  
   <tbody>
     <td *ngFor="let x of collection;">              
         <input type="checkbox" (change)="checkEmails($event,x)" />
     </td>
     <td>{{x.email}}</td>
   </tbody>
<table>

.ts 文件

public groupList: any = [];
checkEmails(event, email) {
    if (event.target.checked) {
      if (this.groupList.length == 0) {
        this.groupList.push(email);
      }
      else {
        this.groupList.push(email);
      }
      console.log("bulkData", this.groupList);
    }
  }

现在列表正在添加到数组中..

但是当取消选择复选框时,我想从数组中删除列表。有谁能够帮我??

在此处输入图像描述

标签: angular6angular5angular7

解决方案


使用拼接功能

checkEmails(event, email) {
if (event.target.checked) {
  this.groupList.push(email);
  console.log("bulkData", this.groupList);
} else {
  for(var i = 0 ; i < this.groupList.length; i++) {
    if(this.groupList[i].email == email.email) {
      this.groupList.splice(i, 1);
    }
  }
  console.log("bulkData1", this.groupList);
}

}

工作示例:https ://stackblitz.com/edit/angular-splice

如需更多说明:https ://love2dev.com/blog/javascript-remove-from-array/


推荐阅读