Arter
Arter

Reputation: 2324

Set passed filter to Angular material table

I have angular material table and search working ok...

Problem is, I have route A and in this route, I send value to the search box in table in route B and they need automatically set filtered data in a table.

I correctly get this value in the table search box, but it's not applied to the table...if I manually add any letter or number, filter working properly

Here is component A

goToRouteB(id): void {
  this.router.navigate(["/routeB"], { state: { data: id } }); //id: is some number
}

And here is component B

ngOnInit() {
  if (history.state.data) {   //history.state.data is passed id
    this.searchKey = history.state.data;
    this.dataSource.filterPredicate = function(data, filter: string): boolean {
      return data.userId.toString() === filter;
    };
  }
}

Upvotes: 1

Views: 982

Answers (4)

sweetnandha cse
sweetnandha cse

Reputation: 961

ngOnInit() {
  if (history.state.data) {   //history.state.data is passed filter values
    this.filterValues = history.state.data;
    this.dataSouce.filter = JSON.stringify(this.filterValues); // <-- add this for multiple filters
  } 
}

Upvotes: 0

StepUp
StepUp

Reputation: 38094

Try to move your logic into ngAfterViewInit:

constructor(private cdr: ChangeDetectorRef) {}

ngAfterViewInit()() {
    if (history.state.data) {   //history.state.data is passed id
        this.searchKey = history.state.data;
        this.dataSource.filterPredicate = function(data, filter: string): boolean 
        {
            return data.userId.toString() === filter;
        };
     }
     this.cdr.detectChanges();
}

As Angular docs says ngAfterViewInit:

Respond after Angular initializes the component's views and child views / the view that a directive is in.

Called once after the first ngAfterContentChecked().

Upvotes: 1

JuNe
JuNe

Reputation: 1997

You need to set the filter to your dataSource. You only define the filter predicate. Set the filter attribute of your dataSource in ngOnInit.

ngOnInit() {
  if (history.state.data) {   //history.state.data is passed id
    this.searchKey = history.state.data;
    this.dataSource.filterPredicate = function(data, filter: string): boolean {
      return data.userId.toString() === filter;
    };
    this.dataSouce.filter = this.searchKey; // <-- add this
  } 
}

Upvotes: 1

Nerijus Pamedytis
Nerijus Pamedytis

Reputation: 134

Why not just use route params and @angular/router provided way of transmitting the data through route params https://angular.io/guide/router#heroes-list-optionally-selecting-a-hero

Upvotes: 0

Related Questions