2

i am trying angular material data table.

As we know filtering happened for each row by default.

If i want to filter column specific, then what should i do?

Should i have to write method for getting all records, then iterate over it and compare specific column?

component.ts


ngOnInit() {
    this.service.getUser().subscribe( results => {
        if(!results){

          return;
        }
        console.log(results);
        this.dataSource = new MatTableDataSource(results);
        this.dataSource.sort = this.sort;
    })


onSearchClear(){
    this.searchKey="";
    this.applyFilter();
  }

  applyFilter(){
    this.dataSource.filter = this.searchKey.trim().toLowerCase();
  }

component.html


<mat-form-field class="search-form-field">
      <input matInput [(ngModel)]="searchKey" placeholder="search by userName" (keyup)="applyFilter()">
    </mat-form-field>
0

2 Answers 2

10

you should use filterPredicate property of MatTableDataSource

after you initialize this.dataSource, define a custom filterPredicate function as follows;

this.dataSource = new MatTableDataSource(results);
this.dataSource.sort = this.sort;
this.dataSource.filterPredicate = function(data: any, filterValue: string) {
  return data.specificColumn /** replace this with the column name you want to filter */
    .trim()
    .toLocaleLowerCase().indexOf(filterValue.trim().toLocaleLowerCase()) >= 0;
};
Sign up to request clarification or add additional context in comments.

5 Comments

this will do exact match....if i want to match a part of any username... suppose mohan is the userName, and if i enter moh....it is not showing that
i have updated my answer to include partial match. please take a look.
where is this.sort coming from?
this.sort it is an instance of MatSort defined within the component class but not shared in the question. My answer just refers to the code provided in the question.
also please see the following material.angular.io/components/sort/overview
8

Check this tutorial and working demo

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.