angularprimengprimeng-table

p-table headers not resetting sorting properly on subsequent p-tabview


I have an array of fixed headers "Tags" which will be dynamically populated as the Tab Headers. Then I have an array of objects "data" which will be looped through each tabs to see if it matches and will populate the table if so. Please find below for a simple summary of my code:

<p-tabView (onChange)="onReset()">
  <p-tabPanel [header]="tag" *ngFor="let tag of tags">
    <p-table #dt [value]="data">
      <ng-template pTemplate="header">
        <tr>
          <th [pSortableColumn]="'Name'">Name
            <p-sortIcon [field]="'Name'"></p-sortIcon>
          </th>
        </tr>
      </ng-template>
      <ng-template pTemplate="body" let-col>
        <tr>
          <td>{{col.Name}}</td>
        </tr>
      </ng-template>
    </p-table>
  </p-tabPanel>
</p-tabView>

My reset function:

import { Table } from 'primeng/table'; 
@ViewChild('dt', {static: false}) table: Table ;
onReset() {
  this.table.reset();
}

There is no issue on the sorting, ascending and descending using pSortableColumn and p-sortIcon.

I want to reset the sorting on the table when I toggle to other tabs and back. However, the sort is only being reset on the first tab's table and not on the subsequent tab. Does anyone have any experience on this? Or maybe point out what I might have done wrongly?

The issue is solved as follows:

@ViewChildren(Table) tables: QueryList<Table>;

resetSort() {
  this.tables.forEach((table) => {
    table.reset();
  });
}



Solution

  • There are more than one table with reference #dt in your page because of *ngFor. When you query tables with @ViewChild('dt', {static: false}) table: Table ; it returns the first table as expected.

    You need a way to call reset() method on currently active tabs table reference.

    First query all tables with:

    @ViewChildren(Table, {static: false}) tables: QueryList<Table>;

    Then call onReset with tab event (see Events here):

    <p-tabView (onChange)="onReset($event)">

    then

    onReset(evt) {
      this.tables[evt.index].reset();
    }