Skip to content Skip to sidebar Skip to footer

How To Add Multiple Filters In Angular Mat Table?

HTML this is the code of my component.html file in which i am adding filters on a table:

To improve and simplify, I put all the FormControls in a FormGroup

form = new FormGroup({
    name: new FormControl(''),
    position: new FormControl(),
    and: new FormControl(false)
  });

To simply subscribe to valueChanges

this.form.valueChanges.subscribe(res => {
  this.dataSource.filter = JSON.stringify(res);
});

my customFilter is like

  customFilter = (data: PeriodicElement, filter: string) => {
    const filterData = JSON.parse(filter);

    //see that if filterData.name=null nameOk=trueconst nameOk =
      data.name.toLowerCase().indexOf(filterData.name.toLowerCase()) >= 0;

    //see that if filterData.position=null positionOk=trueconst positionOk = !filterData.position || data.position == filterData.position;

    if (filterData.and) { //there're no problemoreturn nameOk && positionOk;
    } else { //take account when filterData.name or filterData.position is nullif (filterData.name && filterData.position) return nameOk || positionOk;
      else {
        if (filterData.name) return nameOk;
        if (filterData.position) return positionOk;

        returntrue;
      }
    }
  };

I hope sirve you as inspiration

Post a Comment for "How To Add Multiple Filters In Angular Mat Table?"