How to preset (programmatically) the filter value in primeng datatable

淺唱寂寞╮ 提交于 2019-12-04 17:29:55

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