且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Angular 7中删除该行的单击复选框中的表格的整个行

更新时间:2023-12-04 13:53:12

您必须创建一个数组来跟踪每个复选框的状态.并在每次选中或取消选中复选框时进行更新.

You have to create an array to keep track of the state of each checkbox. And update it every time a checkbox is checked or unchecked.

模板:

<td>
  <input type="checkbox" (click)="toggleSelection($event, i)" [checked]="checkboxes[i]">
</td>

组件:

checkboxes: boolean[];

ngOnInit() {
   this.checkboxes = new Array(this.groups.length);
   this.checkboxes.fill(false);
}

toggleSelection(event, i) {
  this.checkboxes[i] = event.target.checked;
}

此外,每当添加新行时,将另一个复选框条目添加到数组.

Also, add another checkbox entry to the array whenever a new row is added.

addRow(index): void {
  // Other code.
  this.checkboxes.splice(index, 0, false);
}

您可以使用 Array.splice( )从数组中删除元素.

You can use Array.splice() to delete elements from an array.

Array.some()可用于检查是否至少选中了一个复选框,并且 Array.every()可用于检查是否已选中所有复选框.

Array.some() can be used to check if at least one checkbox is selected, and Array.every() can be used to check if all the checkboxes are selected.

delete() {
  var atleastOneSelected = this.checkboxes.some(checkbox => checkbox === true);
  var allSelected = this.checkboxes.every(checkbox => checkbox === true);

  if (!atleastOneSelected) {
    alert("No rows selected.");
    return;
  }

  if (allSelected) {
    alert("At least one row should be present.");
    return;
  }

  // Iterating in reverse to avoid index conflicts by in-place deletion.
  for (let i = this.checkboxes.length-1; i >= 0; i--) {
    // If selected, then delete that row.
    if (this.checkboxes[i]) {
      this.groups.splice(i, 1);
    }
  }

  // Remove entries from checkboxes array.
  this.checkboxes = this.checkboxes.filter(checkbox => checkbox === false);
}

StackBlitz上的实时演示: https://stackblitz.com/edit/angular-abhkyk

Live demo on StackBlitz: https://stackblitz.com/edit/angular-abhkyk