Change background color of a table Row using checkbox

Asked

Viewed 104 times

0

I’m trying to change the color of a row when a checkbox is selected, but when selected only one, the table the entire color is changed, the check remains only in the selected one, but the color is changed in all rows.

I’m using Angular Angular 9 and Angular Material.

HTML:

<ng-container  [matColumnDef]="tableData" *ngFor="let tableData of objectKeys(columnHeader)">
        <div *ngIf="columnHeader[tableData] === 'select'">
          <th mat-header-cell *matHeaderCellDef>
            <mat-checkbox color="primary"
              (change)="$event ? masterToggle() : null "
              #item (click)="check(!item.checked)"
              [checked]="selection.hasValue() && isAllSelected()"
              [indeterminate]="selection.hasValue() && !isAllSelected()"
              [aria-label]="checkboxLabel()">
            </mat-checkbox>
          </th>
          <div *ngIf="columnHeader[tableData] === 'select'">
            <td mat-cell *matCellDef="let element">
              <mat-checkbox color="primary"
                #item [checked]="selection.isSelected(element)"
                (change)="$event ? selection.toggle(element) : null" [aria-label]="checkboxLabel(element)"
                (click)="check(!item.checked)"
                >
              </mat-checkbox>
            </td>
          </div>
        </div>

<tr mat-header-row *matHeaderRowDef="objectKeys(columnHeader)"></tr>
      <tr mat-row *matRowDef="let row; columns: objectKeys(columnHeader);" [ngClass]="{'mat-row': rowChecked}"></tr>

css:

.mat-row {
  background: #2F80ED;
}
  • You could show a visual example?

  • I don’t understand. An image for example?

2 answers

0

At met-Cell inside your table use a [ngClass] or [ngStyle] that can solve your problem, for example:

[ngClass]="{'row-selected': item.checked === true}"

0

Was solved by declaring a variable in TS: selection = new SelectionModel<any>(true, []);

In HTML, the validation is like this: [ngClass]="{'item-selected': selection.isSelected(element)}"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.