Izzy030
Izzy030

Reputation: 59

How to color conditionally a cell for ngx-datatable

I want to change the color of the cell/value if entry is negative. I know there should be more params inside the getCellClass-function but I dont know how to address them correctly since documentation of ngx-datatable is not easy to understand.

TS-File, CSS-File, HTML-File,

getCellClass(row: RowObject) {
  return {
    'ngx-datatable-value-negative': row.value <= 0
  };
}
.ngx-datatable-value-negative {
  color: red !important;
}
<ngx-datatable>
  <ngx-datatable-column [cellClass]="getCellClass" [resizeable]="false" [width]="50" prop="openTimeInHours" [summaryTemplate]="templateForOpen" headerClass="text-right">
    <ng-template ngx-datatable-header-template let-column="column">
      <span title="Tooltip">Column Name</span>
    </ng-template>
    <ng-template let-value="value" ngx-datatable-cell-template>
      <div class="text-right">
        {{value | number: '1.2-2'}}
      </div>
    </ng-template>
  </ngx-datatable-column>
</ngx-datatable>

Upvotes: 0

Views: 5566

Answers (2)

Izzy030
Izzy030

Reputation: 59

I solved my problem. Important was here to understand that the getClass is expecting a defined object. Like in the ngx-documentation I also noticed the return type any.

I log that in my console, so i could address the class correctly

getCellClass(a: any): any {
  console.log(a);
  return {
    'ngx-datatable-value-negative': value <= 0
  };
}

This way i got this object:

{row: {…}, group: undefined, column: {…}, value: -0.5, rowHeight: "auto"}

Further I could use my new created NgxDatatableCell Class for passing the expected object for cellClass

    export class NgxDatatableCell {
    value: number;
}

Finally this is how my method looks now

getCellClass(row: NgxDatatableCell): any {
    return {
        'ngx-datatable-value-negative': row.value < 0,
    };
}

Upvotes: 1

Fernando Flores
Fernando Flores

Reputation: 36

Did you try with [ngclass] selector?

getCellClass(value: number) {
  return {
    'ngx-datatable-value-negative': value <= 0
  };
}
.ngx-datatable-value-negative {
  color: red !important;
}
<ngx-datatable>
  <ngx-datatable-column [resizeable]="false" [width]="50" prop="openTimeInHours" [summaryTemplate]="templateForOpen" headerClass="text-right">
    <ng-template ngx-datatable-header-template let-column="column">
      <span title="Tooltip">Column Name</span>
    </ng-template>
    <ng-template let-value="value" [ngclass]="getCellClass(value)" ngx-datatable-cell-template>
      <div class="text-right">
        {{value | number: '1.2-2'}}
      </div>
    </ng-template>
  </ngx-datatable-column>
</ngx-datatable>

Upvotes: 0

Related Questions