PrimeNG p-table: How to clear p-dropdown filter values when resetting table filters?

我的梦境 提交于 2020-06-13 09:10:39

问题


I am using PrimeNG p-table with a header row that has both input and p-dropdown filters and need to clear the filter values of the input and p-dropdown when calling the .reset() method on the table.

As other's have pointed out (https://stackoverflow.com/a/51402834/5764320), you can use [value] on input elements, but there doesn't seem to be a way to clear any non-input filter values.

How can I reset the filters values for the p-dropdown (and other non-input filter types)?


回答1:


I figured out a simple, clean way that you can use ng-template to accomplish this.

  1. Put your <tr> that has your filters into an ng-template
  2. Add the ng-template to your HTML twice using [ngTemplateOutlet] and *ngIf and assign a value that gets toggled so that one template is used for true and the other for false.
  3. Toggle the value assigned to the templates when you clear your filters.

This "clears" the filters since Angular completely adds and removes the HTML of the templates from the DOM when they are toggled, which means that any values that had previously been used won't exist anymore.

HTML

This assumes you are using <p-table #dt ...> so that dt can be passed with your button click.

Note: leaving some of the p-table related parts and properties out to keep it clean.

<ng-template [ngTemplateOutlet]="FilterRow" *ngIf="showFilters"></ng-template>
<ng-template [ngTemplateOutlet]="FilterRow" *ngIf="!showFilters"></ng-template>
<!-- Whatever your 'tr' content is goes inside this template, this is an abbreviated example -->
<ng-template #FilterRow>
    <tr>
        <th class="text-center">
            <button (click)="clearFilters(dt)">Reset</button>
        </th>
        <th>
            <p-dropdown (onChange)="dt.filter($event.value, col.field, 'equals')"></p-dropdown>
        </th>
        <th>        
            <input pInputText type="text" (input)="dt.filter($event.target.value, col.field,'contains')"/>
        </th>
    </tr>
</ng-template>

TypeScript

...
showFilters = true;
...

clearFilters(dt) {
    this.showFilters = !this.showFilters; // toggle the ng-templates
    dt.reset(); // reset the table
}


来源:https://stackoverflow.com/questions/61919690/primeng-p-table-how-to-clear-p-dropdown-filter-values-when-resetting-table-filt

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