Home > Mobile >  ngClass on an angular mat table row
ngClass on an angular mat table row

Time:09-26

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?

CodePudding user response:

You can use the Safe Navigation Operator ? in Angular template to make sure that such errors (when reading object properties that might be undefined/null) don't appear:

Change you code to:

[ngClass]="{'selectedPlanet': planet?.selected === 'true'}"

Ideally, we should make sure that the template code which depends on some object, should render when the object is available, typically using *ngIf directive.

CodePudding user response:

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>
  • Related