How to highlight a PrimeNG datatable row on click of an image in the column?

7.6k Views Asked by At

I have PrimeNG datatable with 10 columns. Last column contains images. On click of the image I have to highlight the row.

If I add selection mode 'single' in the datatable, on click of row it highlights the row. I do not want that. I want it to be highlighted only when the user clicks on the image at the last column.

<p-column>
        <ng-template let-row="rowData" pTemplate type="body">
          <img src="assets/images/info_icon.jpg" style="height:20px;width:20px">
        </ng-template>
  <p-column>
1

There are 1 best solutions below

0
On

What you have to do is to set a click event on your image that will toggle a property of the associated row. Let's call that property isSelected.

Your HTML code for your image column becomes

<p-column field="isSelected" header="" [style]="{'width':'32px','cursor': 'pointer'}">
  <ng-template pTemplate="body" let-rowData="rowData">
    <img src="https://image.flaticon.com/icons/svg/106/106705.svg" (click)="rowData.isSelected=!rowData.isSelected"/>
  </ng-template>
</p-column>

Then add the rowStyleClass PrimeNG property to your p-dataTable which will call a function, let's name it isRowSelected

<p-dataTable [value]="cars" [rowStyleClass]="isRowSelected">

The isRowSelected function will return a class name, depending on if you selected or unselected the row

isRowSelected(rowData: any) {
  return (rowData.isSelected) ? "rowSelected" : "rowUnselected";
}

Finally, create these two CSS classes : rowSelected and rowUnselected

tr.rowUnselected > td {
  color: black;
  background-color: white !important;
}

tr.rowSelected > td {
  color: black;
  background-color: #dff0d8 !important;
}

Here is a working Plunker