cssangularprimengprimeng-datatable

PrimeNG table - Apply class to row but background-color is not working


I am using PrimeNG table <p-table>. It has virtual scrolling and selectable rows. I want to make the row background-color variable depending on some integer value in the data.

Using this suggestion: https://www.geeksforgeeks.org/angular-primeng-table-styling-certain-rows-and-columns/. I added [ngClass] = 'myRowClass(row.version)':

<ng-template pTemplate="body" let-row>
  <tr 
    style="height:53px;" 
    [ngClass] = 'myRowClass(row.version)'
    [pSelectableRow]="row" 
    (selectstart)="selectRow($event)"
    >

where

public myRowClass(v)
{
  return v<3 ? 'greenBkg' : v<5 ? 'yellowBkg' : 'redBkg';
}

and

::ng-deep .redBkg > tr {
    background-color: 'red' !important;
}

tr.greenBkg{
    background-color: 'green' !important;
}

.yellowBkg{
    background-color: 'yellow' !important;
}

I do see all 3 class names appear in the resulting HTML, but none of them result in color change. Here is an example of what I see in "Inspect":

<tr _ngcontent-nqh-c186="" class="p-element greenBkg p-selectable-row" style="height: 53px;" ng-reflect-ng-class="greenBkg" ng-reflect-data="[object Object]" tabindex="0"><td ....

Here are the versions:

"dependencies": {
    "@angular/animations": "^15.2.4",
    "@angular/cdk": "^15.2.7",
    "@angular/common": "^15.2.4",
    "@angular/compiler": "^15.2.4",
    "@angular/core": "^15.2.4",
    "@angular/flex-layout": "^15.0.0-beta.42",
    "@angular/forms": "^15.2.4",
    "@angular/platform-browser": "^15.2.4",
    "@angular/platform-browser-dynamic": "^15.2.4",
    "@angular/router": "^15.2.4",
    "primeng": "^15.4.1",

Solution

  • From the background-color syntax, it should be:

    background-color: <color>  
    

    Remove the quotes. And your red background will not be functioned correctly. The current styling rule for .redBkg > tr will apply red background to the <tr> element which has the parent element with the class "redBkg".

    Your CSS should be:

    .redBkg {
      background-color: red !important;
    }
    
    .greenBkg {
      background-color: green !important;
    }
    
    .yellowBkg {
      background-color: yellow !important;
    }
    

    Demo @ StackBlitz