Steven Liekens
Steven Liekens

Reputation: 14088

Bind table row's class to checkbox checked state

I created a table where the first column contains a checkbox that is used to select its parent row. I'm trying to style the table so that the whole row has a blue background when selected.

component typescript:

public items = [{ name: 'row 1' }, { name: 'row 2' }, { name: 'etc' }];

component template:

<table>
    <tr>
      <th><!-- selector column --></th>
      <th>Item</th>
    </tr>
    <tr *ngFor="let item of items" [ngClass]="{ selected: selector.checked }">
      <td><input #selector type="checkbox"></td>
      <td>{{item.name}}</td>
    </tr>
</table>

component stylesheet:

tr.selected {
  background-color: blue;
}

Binding ngClass to the checked state of the checkbox in each row appears to work at least partially. When a box is checked, the selected class is added to the row but only after a very noticeable delay.

I believe that the class is not added until after change detection runs and it appears that the act of checking the box does not trigger change detection.

Am I doing something wrong? My component uses the default change detection strategy.

Angular 4.1.3

Here is a Plunkr demo: https://plnkr.co/edit/Tj6IU5?p=preview

Upvotes: 2

Views: 2495

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657338

<ng-container *ngFor="let item of items">
  <tr [ngClass]="{ selected: selector.checked }">
    <td><input #selector type="checkbox"></td>
    <td>{{item.name}}</td>
  </tr>
</ng-container>

or

<tr *ngFor="let item of items; let i=index" [ngClass]="{ selected: inputs[i] }">
  <td><input type="checkbox" (change)="inputs[i] = $event.target.value"></td>
  <td>{{item.name}}</td>
</tr>
...
this.items = ...;
this.inputs = new Array(this.items.length);
this.inputs.fill(false);

Upvotes: 0

Related Questions