Implementing NGX Datatable filtering on all columns

后端 未结 8 750
不知归路
不知归路 2021-02-06 04:21

I\'ve been trying to get this working with no luck. I\'ve been referencing these resources for help: http://swimlane.github.io/ngx-datatable/#filter
https://github.com/swiml

8条回答
  •  暖寄归人
    2021-02-06 04:49

    Using the example TS file for filtering (https://github.com/swimlane/ngx-datatable/blob/master/demo/basic/filter.component.ts) as a foundation, I was able to successfully make it filter all columns dynamically (it will filter all columns without the need to specify them). I've included what I believe to be all the necessary parts for this to work but also trimmed the code down as much as I could to make it easier to understand.

    HTML

    
    
    
    

    TYPESCRIPT

    cols = [{name:'First Name'},{name:'Last Name'},{name:'Address'}];
    data = [];
    filteredData = [];
    
    // dummy data for datatable rows
    dummyData = [
      {firstName:'Daenarys',lastName:'Targaryen',address:'Dragonstone'},
      {firstName:'Sansa',lastName:'Stark',address:'Winterfell'},
      {firstName:'Cersei',lastName:'Lannister',address:'Kings Landing'},
      {firstName:'Brienne',lastName:'Tarth',address:'Sapphire Island'},
      {firstName:'Lyanna',lastName:'Mormont',address:'Bear Island'},
      {firstName:'Margaery',lastName:'Tyrell',address:'Highgarden'}
    ]
    
    ngOnInit(){
      // populate datatable rows
      this.data = this.dummyData;
      // copy over dataset to empty object
      this.filteredData = this.dummyData;
    }
    
    // filters results
    filterDatatable(event){
      // get the value of the key pressed and make it lowercase
      let val = event.target.value.toLowerCase();
      // get the amount of columns in the table
      let colsAmt = this.cols.length;
      // get the key names of each column in the dataset
      let keys = Object.keys(this.dummyData[0]);
      // assign filtered matches to the active datatable
      this.data = this.filteredData.filter(function(item){
        // iterate through each row's column data
        for (let i=0; i

提交回复
热议问题