How to get multiple selected row index in the table in angular 13

46 views Asked by At

I am trying to get multiple selected table row index in my code. But i am getting only one row index. So, How to get mutiple selected row index?

Demo: https://stackblitz.com/edit/angular-ivy-lpwp3n?file=src%2Fapp%2Fapp.component.ts,src%2Fapp%2Fapp.component.html

app.component.html:

<table class="table table-bordered">
<thead></thead>
<tbody>
  <ng-container *ngFor="let row of data1">
    <tr>
      <td><input type="checkbox"  [(ngModel)]="row.isSelected"/></td>
      <td (click)="row.isExpand = !row.isExpand">
        <i *ngIf="!row.isExpand" class="bi-chevron-right"></i>
        <i *ngIf="row.isExpand" class="bi-chevron-up"></i>
        {{ row.name }}
      </td>
    </tr>
    <tr *ngIf="row.isExpand">
      <td colspan="2">
        {{ row.expandData }}
      </td>
    </tr>
  </ng-container>
</tbody>

app.component.ts:

  addSelectedRow() {
    const selectedRowIndexFromTable1 = this.data1.findIndex(
      (row) => row.isSelected
    );
    if (selectedRowIndexFromTable1 !== -1) {
      this.data2.push({
        ...this.data1[selectedRowIndexFromTable1],
        isSelected: false,
      });
    }

    alert(selectedRowIndexFromTable1);
  }

  removeSelectedRow() {
    const selectedRowIndexFromTable2 = this.data2.findIndex(
      (row) => row.isSelected
    );
    if (selectedRowIndexFromTable2 !== -1) {
      this.data2.splice(selectedRowIndexFromTable2, 1);
    }
  }
1

There are 1 answers

0
Hatim Tekri On BEST ANSWER

you need to change the addSelectedRow function, check below code and replace the function with that.

  • Probem with your code

you are using findIndex method which return the index value of first match element and that is the reason it is only adding one record in data2 object

convert that code into fetching multiple records with isSelected condition using filter method and insert all the records into data2 object using loop

addSelectedRow() {
const selectedItems = this.data1.filter((row) => row.isSelected);
this.data2 = [];
selectedItems.forEach((item) => {
  this.data2.push({
    ...item,
    isSelected: false,
  });
});

alert(selectedItems);
}