angularngforng-class

Angular ngFor - Change CSS of the selected row instead of all rows


This is my code:

TS:

  selRow: boolean = false;

HTML:

<tr *ngFor="let user of users" [ngClass]="selRow ? 'selRow' : ''">
  <td class="checkbox-field"><input type="checkbox" (change)="selRow = !selRow" /></td>
  <td class="user-field"> <img [src]="user.userPicture" alt="">
      {{ user.firstName }} {{ user.lastName }}</td>
  <td class="company-field">{{ getCompany(user.companyId) }}</td>
  <td class="email-field">{{ user.email }}</td>
  <td class="roles-field">{{ user.permissionRoles }}</td>
  <td class="edit-field">Edit</td>
  <td class="delete-field"><i class="fas fa-trash-alt"></i></td>
</tr>

CSS:

.selRow {
   background-color: var(--el-lightblue);
}

.selRow .delete-field {
   color: var(--el-red);
}

I'd like the above code to change only the checked row by the checkbox, yet it changes the CSS of all rows. Does anyone know how I can fix this? Here is the example:

Before selected: img-1

After selected: img-2


Solution

  • From your code, you are sharing selRow for each row, hence when you tick the checkbox in a row, other rows' checkboxes will also automatically checked.

    Instead, what you need are:

    1. selRows: An array to store selected index.
    2. toggleSelectedRows: An method to add/remove the index from selRows.
    3. isSelectedRow: Check whether the index is added in selRows.
    selRows: number[] = [];
    
    toggleSelectedRows(i: number) {
      let index = this.selRows.findIndex((x) => x == i);
    
      if (index == -1) this.selRows.push(i);
      else this.selRows.splice(index, 1);
    }
    
    isSelectedRow(i: number) {
      return this.selRows.findIndex((x) => x == i) > -1;
    }
    
    <tr
      *ngFor="let user of users; let i = index"
      [ngClass]="isSelectedRow(i) ? 'selRow' : ''"
    >
      <td class="checkbox-field">
        <input type="checkbox" (change)="toggleSelectedRows(i)" />
      </td>
      
      ...
    </tr>
    

    Sample StackBlitz Demo