1
votes

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;
    };
  }
}
4

4 Answers

1
votes

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
  } 
}
1
votes

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().

0
votes

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

0
votes
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
  } 
}