问题
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.
- Put your
<tr>
that has your filters into anng-template
- 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 fortrue
and the other forfalse
. - 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