Search code examples
user-interfaceangular5primengprimeng-datatable

add button and get column selected on p-datatable


I have a p-datatable as follows

<p-dataTable [(value)]="test.TestDetails" [paginator]="true" [rows]="3" [rowsPerPageOptions]="[3,6,9]">
<p-column header="Test1" field="test1"></p-column>
<p-column header="Test2" field="test2"></p-column>
<p-column header="Test3" field="test3"></p-column>
<p-column header="Test4" field="test4" ></p-column>

<p-column  >
  <ng-template let-TestDetails="rowData" pTemplate="body">
    <button  type="button" class="ui-button-reset-transparent" pButton (click)="SelectTest()"  ></button>
  </ng-template>
</p-column>

</p-dataTable>

If I click on the button the row should get selected/highlighted automatically. How can I achieve it ?


Solution

  • Use selection directives and add selectionMode="single" [(selection)]="selectedRow" to your p-dataTable.

    selectedRow will contain the data of the row you want to be selected. Send the rowIndex to your SelectTest method so that you'll know which item of test.TestDetails you have to assign to selectedRow :

    SelectTest(rowIndex) {
      this.selectedRow = this.test.TestDetails[rowIndex];
    }
    

    See Plunker