How to filter a mat-tree component Angular Material 6.0.1

前端 未结 4 637
醉酒成梦
醉酒成梦 2020-12-28 08:47

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

4条回答
  •  没有蜡笔的小新
    2020-12-28 09:10

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

提交回复
热议问题