父模块的相关部分,列表组件:
...
searchKey: string;
listComponent: IList;
ngAfterViewInit() {
this.listComponent = new RequestListComponent(this.service);
}
public doFilter() {
this.listComponent.doFilter(this.searchKey.trim().toLowerCase());
}
ListComponent的相关HTML:
<mat-form-field class="side-by-side" id="filter">
<input matInput name="filter" [(ngModel)]="searchKey" (keyup)="doFilter()" placeholder="Search Text" autocomplete="off">
</mat-form-field>
子组件的类型为IList,即列表接口。此接口创建成功,显示数据,数据可排序,但过滤不起作用。
子组件的相关部分,请求列表:
@ViewChild(MatSort, {static: false}) sort: MatSort;
@ViewChild(MatPaginator, {static: false}) paginator: MatPaginator;
constructor(private service: RequestTableService) {
this.displayedColumns = this.service.ColumnsToDisplay(RequestType.STATUS); }
}
ngOnInit(){
this.service.getTable(RequestType.STATUS, this.active).subscribe(res =>{
this.dataSource.data = res as StatusRequest[];
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
this.dataSource.filterPredicate = this.tableFilter();
});
refreshTable(){
this.service.getTable(RequestType.STATUS, this.active).subscribe(res =>{
this.dataSource.data = res as StatusRequest[];
});
}
public doFilter(value: string){
this.dataSource.filter = value;
}
tableFilter(): (data: any, filter: string) => boolean {
let filterFunction = function(data, filter): boolean{
return data.toLowerCase().indexOf(filter) !== -1;
}
return filterFunction;
}
数据服务:
constructor(private http: HttpClient) { }
public getTable(selectedRequestType: string, active: boolean):Observable<any> {
let params = this.getParamsByUserRole(active);
return this.http.get(this.getRouteByRole(selectedRequestType), {params});
}
我认为request-list.html不相关。
将doFilter()的值记录到控制台应能正常工作,显示来自matInput的字符串的值,该值在父模块中设置searchKey字符串。
我觉得这与filterPredicate有关,但是我是打字稿菜鸟,不知道为什么。
编辑:问题在于datasource.data数组为空,甚至为null,这取决于其初始化方式。我的数据服务有问题吗?更新了代码以反映如何返回数据。为了清楚起见,在ngOnInit中的service.getTable()调用之后,该表将填充数据。