I\'m using mat-tree angular material component. It\'s a nice component with some very useful features like, multi-select, expand all/collapse all. I was not able to find any
I am able to filter a tree by using simple recursion. Below are the code snippets:
The filter() function is called on (keyup) of input type="text". cloneDeep function is imported from lodash import * as cloneDeep from 'lodash/cloneDeep';
this.searchString is the string value for the filter text.
filter() {
const clonedTreeLocal = cloneDeep(this.clonedTree);
this.recursiveNodeEliminator(clonedTreeLocal);
this.dataSource.data = clonedTreeLocal;
this.treeControl.expandAll();
}
The tree structure is defined by the interface
export interface ITreeDataStructure {
Id?: number;
name: string;
type: string;
children?: Array;
}
The actual filtering is done by the function recursiveNodeEliminator
recursiveNodeEliminator(tree: Array): boolean {
for (let index = tree.length - 1; index >= 0; index--) {
const node = tree[index];
if (node.children) {
const parentCanBeEliminated = this.recursiveNodeEliminator(node.children);
if (parentCanBeEliminated) {
if (node.name.toLocaleLowerCase().indexOf(this.searchString.toLocaleLowerCase()) === -1) {
tree.splice(index, 1);
}
}
} else {
// Its a leaf node. No more branches.
if (node.name.toLocaleLowerCase().indexOf(this.searchString.toLocaleLowerCase()) === -1) {
tree.splice(index, 1);
}
}
}
return tree.length === 0;
}