Search code examples
angularfiltertreeangular6angular-material2

How to filter a mat-tree component Angular Material 6.0.1


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 tree filtering feature in any of their APIs. Has anyone came across this feature or done any work around to get mat-tree filter?

enter image description here


Solution

  • I solved the problem by creating a new data source(filtered).

    stackblitz sample

    I will explain the example of the shared link: I filtered the data with filter(filterText: string) in ChecklistDatabase and triggered a dataChange event. Then datasource.data was changed by a handled event in TreeChecklistExample. Thus the data source has been modified.

    filter(filterText: string) {
      let filteredTreeData;
    
      if (filterText) {
        filteredTreeData = this.treeData.filter(
          //There is filter function in the sample
        );
      } else {
        filteredTreeData = this.treeData;
      }
    
      // file node as children.
      const data = this.buildFileTree(filteredTreeData, '0');
    
      // Notify the change. !!!IMPORTANT
      this.dataChange.next(data);
    }