Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tree like checkbox and search filter implementation in angular?

What I have:

I have implemented a tree like structure with checkbox selection and search filter. The hierarchy is of fixed 3 levels(Parent->Intermediate->Child). Selecting checkboxes is working perfectly fine(with all feature including indeterminate sign on checkbox when some of nodes selected or tick sign when all childs are selected).

I have also applied a search filter on the tree structured data with a custom angular pipe.

The problem happens when I apply search filter, the selection of checkboxes misbehaves. Also it do not get selected. The indeterminate sign also not working as expected.

A very good reference is this: https://angular2-tree.readme.io/docs/filtering, although I can't use this library, but I wanted to have exact similar feature.

My requirement is that user should able to filter the nodes and select the node

What I tried:

I have created this Stackblitz link. Please have a look at this.

Any help or suggestion would be much appreciated. Thanks!

like image 734
Dungeon Avatar asked Oct 18 '25 19:10

Dungeon


1 Answers

why not use a mat-tree? based in this SO about tree-view

We need two recursive functions:

setChildOk(text: string, node: any) {
    node.forEach(x => {
      x.ok = x.name.indexOf(text) >= 0;
      if (x.parent) this.setParentOk(text, x.parent,x.ok);
      if (x.children) this.setChildOk(text, x.children);
    });
  }
  setParentOk(text, node,ok) {
    node.ok = node.ok || ok || node.name.indexOf(text)>=0;
    if (node.parent) this.setParentOk(text, node.parent,node.ok);
  }

We can add an input "search" and make a function

 <input matInput [ngModel]="search" 
       (ngModelChange)="search=$event;setChildOk($event,dataSource.data)">

Well, now, we show the nodes is node.ok or if !search

<mat-tree-node *matTreeNodeDef="let node" matTreeNodeToggle 
      [style.display]="!search || node.ok?'block':'none'">

And

<mat-nested-tree-node *matTreeNodeDef="let node; when: hasChild" 
          [style.display]="!search || node.ok?'block':'none'">

See in this stackblitz

like image 63
Eliseo Avatar answered Oct 20 '25 10:10

Eliseo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!