我在Angular应用程序上使用PrimeNg DataTable。
我想保存过滤器,当返回到组件时,恢复过滤器并在col标头上显示过滤器值。
其实我正在尝试这个,但它不起作用:
@ViewChild(DataTable) candTable: DataTable;
storeFilters(event: any) {
this._candidatureService.storeFilters(event.filters);
}
restoreFilters(){
let filtersStored = this._candidatureService.restoreFilters();
if(filtersStored){
this.candTable.filters = filtersStored;
}
}
这里的逻辑是你必须在sessionStorage中保存过滤器,或者你也可以将它保存在localStorage中。这取决于您的要求。
每当您对过滤器进行任何更改时,Primeng表都会触发一个表事件Object。您可以在其中找到Filter行排序顺序等的所有细节。
我在这里有两个文本框,另一个是过滤器的下拉列表。我们要在文本框和selct框中显示过滤器的唯一方法是,我们必须采用两个变量。我们将与ngModel绑定。如果你有10列都有过滤器,那么你将需要采取10个变量,或者你可以创建一个对象。
<p-table #dt [columns]="selectedColumns"
[value]="data"
[lazy]="true"
(onLazyLoad)="loadDataLazily($event)"
[paginator]="true"
[rows]="10"
[totalRecords]="totalRecords"
[filterDelay]="500">
<ng-template pTemplate="header">
<tr>
<th *ngFor="let col of selectedColumns" [ngSwitch]="col.field">
{{col.header}}
</th>
</tr>
<tr>
<th *ngFor="let col of selectedColumns" [ngSwitch]="col.field">
<input *ngSwitchCase="'NAME'"
type="text"
[(ngModel)]="name"
(input)="dt.filter($event.target.value, 'NAME')"
[value]="dt.filters['NAME']?.value">
<p-dropdown *ngSwitchCase="'USER'"
[options]="users"
[style]="{'width':'100%'}"
[(ngModel)]="user"
(onChange)="dt.filter($event.value, 'USER', 'equals')">
</p-dropdown>
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-i="rowIndex" let-suite>
....
</ng-template>
</p-table>
// This is how you can reset filter.
<button class="btn btn-default btn-sm" (click)="resetTable(dt)">
<i class="fa fa-undo"></i> Reset Filter</button>
public user;
public name
public cachedTableEvent:any;
ngOnInit() {
this.cachedTableEvent = JSON.parse(sessionStorage.getItem("filter"));
}
loadDataLazily(e: any) {
sessionStorage.setItem("filter",JSON.stringify(e));
if(this.cachedTableEvent){
e = this.cachedTableEvent;
for (var key in this.cachedTableEvent['filters']) {
if (this.cachedTableEvent['filters'].hasOwnProperty(key)) {
switch(key){
case "USER":
this.user = this.cachedTableEvent['filters'][key].value;
case "NAME":
this.name = this.cachedTableEvent['filters'][key].value;
}
}
}
this.cachedTableEvent = null;
}
fetchRecordFromBackend(e);
}
resetTable(e: any) {
this.name = null;
this.user = null;
e.reset();
}
这段代码非常适合我。可能对你有所帮助。