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

[亡魂溺海] 提交于 2019-12-11 04:32:19

问题


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:


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



来源:https://stackoverflow.com/questions/46098069/how-to-highlight-a-primeng-datatable-row-on-click-of-an-image-in-the-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!