将通过的过滤器设置为Angular材质表

时间:2019-10-17 10:11:13

标签: angular angular-material

我有角形材料表,可以搜索了……

问题是, 我有route A,在这条路线中,我将值发送到route B中表中的搜索框,他们需要在表中自动设置过滤后的数据。

我在表格搜索框中正确获得了该值,但是它不适用于表格...如果我手动添加任何字母或数字,则过滤器会正常工作

这里是component A

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

这是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 个答案:

答案 0 :(得分:1)

尝试将您的逻辑移至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:

  

在Angular初始化组件的视图和子级后响应   视图/指令所在的视图。

     

在第一个ngAfterContentChecked()之后调用一次。

答案 1 :(得分:1)

您需要将过滤器设置为dataSource。您仅定义过滤谓词。在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
  } 
}

答案 2 :(得分:0)

为什么不仅仅使用路由参数,而@angular/router提供了通过路由参数https://angular.io/guide/router#heroes-list-optionally-selecting-a-hero传输数据的方式

答案 3 :(得分:0)

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