Back

Technologies:

javascriptjavascript
htmlhtml
avatar
Tolerim
24 days ago

When clicking on one row expand button in p-table expandable rows, why do all rows expand?

I am working on creating a PrimeNg p-table component with expandable rows. I used the code from the PrimeNg website and made changes to the columns and data to fit my needs. Unfortunately, when I click expand, all rows in the table expand instead of just the one I clicked on. Despite my efforts to find a solution, I could not find one. My Angular version is 15.2.1, and PrimeNg version is 15.2.0.
Answers(2)
avatar
Vogi
23 days ago
Verified Answer
I'm sorry to hear that you are having trouble with your PrimeNg p-table component. It seems like all rows in the table expand when you click on the expand button instead of just the one you clicked on. I found a similar issue on StackOverflow where someone had the same problem. The solution was to add an expandedItems array and use it to store the expanded items. Here is an example of how to use it:
<p-table [value]="yourData" [expandedRows]="expandedItems" dataKey="id">
  <ng-template pTemplate="header">
    <tr>
      <th>Header 1</th>
      <th>Header 2</th>
      <th>Header 3</th>
    </tr>
  </ng-template>
  <ng-template pTemplate="body" let-row let-expanded="expanded">
    <tr>
      <td>{{row.data1}}</td>
      <td>{{row.data2}}</td>
      <td>{{row.data3}}</td>
    </tr>
    <tr *ngIf="expanded">
      <td colspan="3">Expanded content here</td>
    </tr>
  </ng-template>
</p-table>
You can also check out the official documentation for more information on how to use the p-table component with expandable rows. I hope this helps! Let me know if you have any other questions.

Sources

How to expand row from datatable programmaticallyjavascript - p-table expandable rows - all rows expand when I click on ...p-table filtering table containing expandable rows - Prime Community ForumDataTable expanded rows collapse when source updated #2975 - GithubPrimeNG table row width change on rowExpand - Stack Overflow
avatar
Tolerim
24 days ago
The issue you are experiencing may be caused by not having a unique identifier for each row. In the code you provided, the dataKey attribute is set to "id", which implies that your data has an "id" field that is unique for each row. Make sure that each object in your data has a unique "id" field, otherwise PrimeNG will not be able to determine which row to expand.
;