I'm trying to implement a search function (filtering) in a material flat tree component, but nothing happens when I update my dataSource. I feel like I have tried all different methods and can't get it to work. All I want to do is replace the data and rerender the tree. What am I doing wrong?
I've tried different solutions but many seem outdated, e.g:
this.dataSource.data = null;
this.dataSource = new MatTreeFlatDataSource(this.treeControl, this.treeFlattener);
this.dataSource.data = [];
which gives an error when trying to flatten the null object.
interface FlatNode {
expandable: boolean;
name: string;
level: number;
}
@Component({
selector: 'app-category-list',
templateUrl: './category-list.component.html',
styleUrls: ['./category-list.component.scss']
})
export class CategoryListComponent {
dataChange = new BehaviorSubject<Category[]>([]);
private _transformer = (node: Category, level: number) => {
return {
expandable: !!node.children && node.children.length > 0,
name: node.name,
level: level,
};
}
treeControl = new FlatTreeControl<FlatNode>(
node => node.level, node => node.expandable);
treeFlattener = new MatTreeFlattener(
this._transformer, node => node.level, node => node.expandable, node => node.children);
dataSource = new MatTreeFlatDataSource(this.treeControl, this.treeFlattener);
constructor(private categoryListService: CategoryListService) {this.dataSource.data = this.categoryListService.getTopCategories();}
hasChild = (_: number, node: FlatNode) => node.expandable;
ngOnInit() {
this.dataChange.subscribe(data => {
this.dataSource.data = data;
});
}
}
searchCategory(list: Category[]) {
this.dataChange.next(list);
}
}
I want the dataSource to update and re-render the material tree.