Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 307
SatAj Avatar asked May 30 '18 18:05

SatAj


3 Answers

After I have spent several days on the same task here are some tips i can give: I am using input event to follow the user input:

<input matInput class="form-control" 
  (input)="filterChanged($event.target.value)" 
  placeholder="Search Skill">

On this filter I attached a subject so i can subscribe to it:

searchFilter: Subject<string> = new Subject<string>();
filterChanged(filter: string): void {
  this.searchFilter.next(filter);
}

To make it smooth for the user, usually, we want to delay the search execution which you can do with debounceTime.

this.searchFilter.pipe(debounceTime(500), distinctUntilChanged())
  .subscribe(value => {
    if (value && value.length >= 3) {
      this.filterByName(value);
    } else {
      this.clearFilter();
    }
});

To perform the search, I hide and show the nodes using a css class. This is done directly on the presentation collection which is flat and very easy to filter.

treeControl: FlatTreeControl<SkillFlatNode>;
this.treeControl.dataNodes

First, I hide all and then show only those that match the criteria. Finally, I want to show their parents, but this is specific for my tree structure.

private filterByName(term: string): void {
  const filteredItems = this.treeControl.dataNodes.filter(
    x => x.value.DisplayName.toLowerCase().indexOf(term.toLowerCase()) === -1
  );
  filteredItems.map(x => {
    x.visible = false;
  });

  const visibleItems = this.treeControl.dataNodes.filter(
    x => x.value.IsSkill &&
    x.value.DisplayName.toLowerCase().indexOf(term.toLowerCase()) > -1
  );
  visibleItems.map( x => {
    x.visible = true;
    this.markParent(x);
  });
}

Finally, here is the clear filter:

private clearFilter(): void {
  this.treeControl.dataNodes.forEach(x => x.visible = true);
}

Don't make the same mistake like I did and try to filter the input collection (this.dataSource.data in my case) because you will lose your selection or you will have to map it back to the presentation. Here is my initial data:

this.treeFlattener = new MatTreeFlattener(
  this.transformer, this._getLevel, this._isExpandable, this._getChildren
);
this.treeControl = new FlatTreeControl<SkillFlatNode>(
  this._getLevel, this._isExpandable
);
this.dataSource = new MatTreeFlatDataSource(
  this.treeControl, this.treeFlattener
);

skillService.dataChange.subscribe(data => {
  this.dataSource.data = data;
});
like image 64
ganelon Avatar answered Oct 16 '22 18:10

ganelon


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);
}
like image 12
mfatih Avatar answered Oct 16 '22 18:10

mfatih


Stackblitz link for mat-tree filter

If Anyone need to visually filter the mat tree without modifying the datasource, then go for this solution.

Basically the idea is to hide the nodes which are not part of the search string.

Input field

<input [(ngModel)]="searchString" />

call filter function for leaf node(this is done in the first mat-tree-node)

<mat-tree-node
   *matTreeNodeDef="let node"
   [style.display]="
      filterLeafNode(node) ? 'none' : 'block'
   "
   .....
   ......

call filter function for the nodes other than leaf node(this is done in the second mat-tree-node)

<mat-tree-node
   *matTreeNodeDef="let node; when: hasChild"
   [style.display]="filterParentNode(node) ? 'none' : 'block'"
   .....
   .....

filterLeafNode function

filterLeafNode(node: TodoItemFlatNode): boolean {
   if (!this.searchString) {
     return false
   }
   return node.item.toLowerCase()
     .indexOf(this.searchString?.toLowerCase()) === -1
}

filterParentNode function

filterParentNode(node: TodoItemFlatNode): boolean {

  if (    
    !this.searchString ||
    node.item.toLowerCase()
     .indexOf(
       this.searchString?.toLowerCase()
     ) !== -1
  ) {
    return false
  }
  const descendants = this.treeControl.getDescendants(node)

  if (
    descendants.some(
      (descendantNode) =>
        descendantNode.item
          .toLowerCase()
          .indexOf(this.searchString?.toLowerCase()) !== -1
    )
  ) {
    return false
  }
  return true
}
like image 9
Amith B Avatar answered Oct 16 '22 17:10

Amith B