Search code examples
htmlcssangulartypescriptmat-table

ngClass on an angular mat table row


i want to use the select-option of an angular select to change the css-class of a specific row of an angular material table.

My selection works perfectly and i can give the planet on select an "selected=true" property. (all other set to false). Now i want to change the css-class (red border) of the specific row, where the object has the "selected" property = true.

my html looks like this:

<table mat-table [dataSource]="planets" [trackBy]="trackById" class="mat-elevation-z8" id="planetList">

//all ng containers

<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row [ngClass]="{'selectedPlanet': planet.selected === 'true'}" *matRowDef="let row; columns: displayedColumns;"></tr>
css:
.selectedPlanet {border-color: red;}

But i have the problem, that my console throws an error, something like "ctx_r7.planet is undefined". i dont know how to use ngClass here on a mat table to change the row. Has anyone an idea, how i can solve this?


Solution

  • You need a safe Navigation as your planet is undefined.

    <tr mat-row [ngClass]="{'selectedPlanet': planet?.selected === 'true'}" *matRowDef="let row; columns: displayedColumns;"></tr>
    

    You don't have the planet defined I assumed the entry row has selected property so use the row property to access any attribute

    <tr mat-row [ngClass]="{'selectedPlanet': row?.selected === 'true'}" *matRowDef="let row; columns: displayedColumns;"></tr>