Muhammad Arslan
Muhammad Arslan

Reputation: 472

Issues in custom filtering boolean value in primeng Table

I am using primeng Table for displaying data in my Angular app, the issue i have right now is i have to use filter but with conditions, for example if user type 0, 1, or 2, i have to display data based on this, what i am trying is this

        if(value == 0) {
            table.filter(value, fieldName, 'equals');
        } else if(value == 1) {
            table.filter(0, fieldName, 'gt');
            table.filter(false, 'array[0].fieldName',  'equals');
        } else if(value == 2) {
            table.filter(0, fieldName, 'gt');
            table.filter(true, 'array[0].fieldName',  'equals');
        }

if user type 0 its filtering fine, but the issue is when he type 1 or 2 because i have to filter from 2 fields, i am not sure what i am trying to do is possible in primeng or not.

Upvotes: 1

Views: 4818

Answers (1)

Kimserey Lam
Kimserey Lam

Reputation: 121

table.filter(...) works on a single column.

It is designed to filter the data on a particular column. The following is the type definition of the filter function:

filter(value: any, field: any, matchMode: any): void;

But you are on the right path as it is possible to set different filters, one on each column, which are then combined with AND to filter the data of the table.

For example the following function can filter using multiple columns:

filter(dt) {
  dt.filter('Blue', 'color', 'equals');
  dt.filter('Bmw', 'brand', 'equals');
}

Here's an example of a template:

<p-table #dt [value]="cars">
  <ng-template pTemplate="header">
     <tr>
      <th>
        Color
      </th>
      <th>
        Brand
      </th>
     </tr>
   </ng-template>
   <ng-template pTemplate="body" let-car>
     <tr>
      <td>{{car.color}}</td>
      <td>{{car.brand}}</td>
     </tr>
   </ng-template>
</p-table>

<button (click)="filter(dt)">Get Blue Bmw</button>

And a complete component:

export class MyComponent {
  cars: {
    color: string;
    brand: string;
  }[];

  constructor() {
    this.cars = [{
      color: "blue",
      brand: "bmw"
    },{
      color: "red",
      brand: "bmw"
    }];
  }

  filter(dt) {
    dt.filter('Blue', 'color', 'equals');
    dt.filter('Bmw', 'brand', 'equals');
  }
}

The button will apply the filter on multiple columns which will result in data being filtered with color equals Blue AND brand equals Bmw.

Edit: It works the same for boolean.

cars: {
  color: string;
  brand: string;
  enable: boolean;
}[];

filter(dt) {
  dt.filter('Blue', 'color', 'equals');
  dt.filter('Bmw', 'brand', 'equals');
  dt.filter(true, 'enable', 'equals');
}

In the code you pasted 'array[0].fieldName' is treated as a literal due to the quotes, therefore it looks for a field name "array[0].fieldName" and does not evaluate it.

Upvotes: 1

Related Questions