0

How can I add a class to a cell depending on field value?

<p-dataTable [value]="invoices" tableStyleClass="table-invoices">
    <p-column field="status" header="Status" styleClass="mini status">
        <ng-template pTemplate="body" let-col let-inv="rowData">
            {{inv.status}}
        </ng-template>
    </p-column>
</p-dataTable>

I know how to add class to all cells in a column, but I need to give a class to cells (<td>) individually, depending on the value stored in status, so some cells in a column will have the class and some others in the same column won't.

Plunker

Edited: I know how to give a class to a HTML element inside the <td>, but I want to know if it's possible to give a class to the <td> itself.

mariogl
  • 1,195
  • 1
  • 10
  • 24

2 Answers2

0

You can style a template:

<p-dataTable [value]="invoices" tableStyleClass="table-invoices">
    <p-column field="status" header="Status" styleClass="mini {{rowData}}" >
        <ng-template pTemplate="body" let-col let-inv="rowData">
            <div [class.decorated]="inv.status == 1">{{inv.status}}</div>
        </ng-template>
    </p-column>
</p-dataTable>

plunkr

hiper2d
  • 2,814
  • 1
  • 18
  • 14
0

In order to style the whole cell you will have to find the TD element that hosts your ng-template. To do this, I implemented a directive:

import { Directive, ElementRef, Renderer, Input, OnInit } from '@angular/core';

@Directive({
    selector: '[cellFormatting]'
})
export class CellFormattingDirective {
    @Input() cellFormatting: any;

    constructor(private el: ElementRef, renderer: Renderer) {

    }

    ngOnInit() {
        let target = this.el.nativeElement;
        let td = target.closest('td');
        if (td) {
            //apply some conditions here using data.cellFormatting
            td.style.backgroundColor = 'darkorange';
            td.style.color = 'white';
        }
    }
}

The I used it in the markup as :

<ng-template let-col let-data="rowData" pTemplate="body">
    <div [id]="col.field" class="cell-content" [cellFormatting]="data">
        <div [innerHTML]="data[col.field]" class="center-parent-screen"></div>
    </div>
</ng-template>

Once you have a reference to the TD element, you can apply any CSS transformations you want.

This approach does not feel like the "Angular" way, but currently, this is the only way I managed to accomplish this.

dpdragnev
  • 2,011
  • 2
  • 28
  • 55