angularngx-datatable

Ngx-datatable cellClass not working


I try to append my custom css to ngx-datatable cell.

<ngx-datatable-column 
  *ngFor="let column of tableOptions.columnDefs"
  [cellClass]="'my-custom-cell'"
  ...

Css for my-custom-cell :

.my-custom-cell{
  padding: 0;
}

In dev tools I can see datatable-body-cell has classes

class="datatable-body-cell my-custom-cell sort-active"

Problem is that no css is overridden


Solution

  • Probably you're facing an issue about View Encapsulation.

    ngx-datatable uses ViewEncapsulation.None on it's styling. You can add your .my-custom-cell style definition to ./src/styles.(s)css or you can also set your component's encapsulation to None.

    You can check details of view encapsulation from angular guide if you don't know about it already.


    Edit (response for Tom's comment)

    I also don't want such a solution but unfortunately it seems this is the way... I've prepared a demo app which shows what I'm trying to tell.

    .my-custom-cell assigned to name column.

    .my-custom-cell-global assigned to gender column.

    ./app/demo-component.ts

    <ngx-datatable-column name="name" [cellClass]="'my-custom-cell'">
      <ng-template ngx-datatable-cell-template let-value="value">
        {{value}}
      </ng-template>
    </ngx-datatable-column>
    <ngx-datatable-column name="gender" [cellClass]="'my-custom-cell-global'">
      <ng-template ngx-datatable-cell-template let-value="value">
        {{value}}
      </ng-template>
    </ngx-datatable-column>
    

    ./app/demo-component.scss

    .my-custom-cell {
      background: red;
    }
    

    ./styles.scss

    .my-custom-cell-global {
      background: #e6f2ff;
    }
    

    As you can see red background is not assigned to name column. But gender column gets blue background color.

    That's because view encapsulation tells the cli to compile the .my-custom-cell class as shown as below:

    .my-custom-cell[_ngcontent-c176]{background:red}
    

    But DatatableComponent is using ViewEncapsulation.None. If you inspect one of the cells in name column then you can see that datatable-body-cell which has .my-custom-cell class, doesn't have [_ngcontent-c176] attribute. So the class is not applied.

    If you uncomment encapsulation line:46 then you'll see that [_ngcontent-c176] attribute has gone from compiled .my-custom-cell, and name column gets the style successfully.

    Let me know if you find another suitable way.