Using angular (4.1.3) and primeng (4.0.3) datatable I need to set the filter value (e.g. from URL parameter).
There is a pretty good docu on custom filters by primeng (https://www.primefaces.org/primeng/#/datatable/filter). I've tried to implement it similarly with a primeng InputText component as a custom filter:
<p-dataTable
[value]="licenses" scrollable="true"
exportFilename="licenses"
sscrollHeight="60vh" [paginator]="true" [rows]="20" [pageLinks]="10" [rowsPerPageOptions]="[5,10,20,50,100,999999]" #dt>
<p-column [style]="{'width':'180px'}" [sortable]="true" field="customerId" header="Customer ID" [filter]="true" filterMatchMode="contains" filterPlaceholder="Search">
<ng-template pTemplate="filter" let-col>
<input type="text" pInputText [(ngModel)]="custFilter" style="width:100%" (onChange)="dt.filter($event.value,col.field,col.filterMatchMode)" class="ui-column-filter"/>
</ng-template>
</p-column>
...
</p-dataTable>
Now I have an input field, which looks like the "regular" one and even has a "custFilter" model from my component as pre-selected filter value.
The only issue is, this custom filter does not work. It just does not filter regardless of which value I enter (in opposite to the "regular" primeng datatable filter). Here is a screenshot
While further debugging the type script code I have found a way to do the filtering. The input should be like following:
<input #filtr type="text" pInputText [(ngModel)]="custFilter" style="width:100%" (input)="dt.filter($event.srcElement.value,col.field,col.filterMatchMode);" class="ui-column-filter"/>
The main difference is, the (input) instead of (onChange) and "$event.srcElement.value" instead of just "$event.value"
Furthermore to achieve initial filtering after the page and data is initially loaded an input event has to be dispatched from within an according component:
...
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
...
export class DataComponent implements OnInit {
@ViewChild(('dt')) dt: DataTable;
@ViewChild(('filtr')) filtr: ElementRef;
private initData(): void {
this.dataService
.getData()
.then(data => {
this.data = data;
//After the data is loaded, the filtering has to be triggered.
//A timeout is needed to avoid weird browser console logs if data isn't fully loaded into datatable yet before filtering
setTimeout(() => {
//console.log(this.filtr);
var event = new Event('input', {
'bubbles': true,
'cancelable': true
});
this.filtr.nativeElement.dispatchEvent(event);
//One could also call "filter" directly instead of dispatching an input event
//Working example: this.dt.filter(this.custFilter,"customerId", "contains");
//But emmiting an event seems to be better, because no filterMatchMode has to be
//hardcoded and is taken from template
}, 50);
}).catch(this.handleError);
}
ngOnInit(): void {
this.initLicenses();
}