PrimeNG Dynamic Column Filtering

Josh picture Josh · Feb 21, 2018 · Viewed 26.9k times · Source

I currently have the following PrimeNG TurboTable:

<p-table [value]="People" >
  <ng-template pTemplate="header">
    <tr>
      <th>Name</th>
      <th>Age</th>
      <th>Height</th>
    </tr>
  </ng-template>
  <ng-template pTemplate="body" let-col>
    <tr>
      <td>{{col.Name}}</td>
      <td>{{col.Age}}</td>
      <td>{{col.Height}}</td>
    </tr>
  </ng-template>
</p-table>   

I need to be able to filter by the Age column when the page loads, how would I do this? All the examples I could find show use an (input) or (onChange) tag like so (taken from their website):

<input type="text" pInputText size="50" placeholder="Global Filter" (input)="dt.filterGlobal($event.target.value, 'contains')" style="width:auto">

How can I filter by column on load rather than on an element changing?

Here's the page I'm referencing: https://www.primefaces.org/primeng/#/table/filter

Thank you!

Answer

Shailesh Sangekar picture Shailesh Sangekar · Jul 26, 2018

When you use static columns you have to specify the column name for the filter at the table level. Add [globalFilterFields]="['Age']" at table level.

 <p-table #dt [value]="data" [globalFilterFields]="['Age']">
                <ng-template pTemplate="caption">
                    <div style="text-align: right">
                        <i class="fa fa-search" style="margin:4px 4px 0 0"></i>
                        <input type="text" pInputText size="50" placeholder="Global Filter" (input)="dt.filterGlobal($event.target.value, 'contains')"
                            style="width:auto">
                    </div>
                </ng-template>
                <ng-template pTemplate="header">
                    <tr>
                        <th>Name</th>
                        <th>Age</th>
                        <th>Height</th>
                    </tr>
                </ng-template>
                <ng-template pTemplate="body" let-col>
                    <tr>
                        <td>{{col.Name}}</td>
                        <td>{{col.Age}}</td>
                        <td>{{col.Height}}</td>
                    </tr>
                </ng-template>
            </p-table>