如何使用angular2中的递归过滤树的子节点

时间:2018-02-15 15:47:58

标签: angular tree angular2-template angular2-directives

--**app.component.ts**
import { Component,OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';


@Component({
  selector: 'my-app',
  templateUrl:'./app.component.html'
})
export class AppComponent implements OnInit {
  Tree: any;
  private searchText$ = new Subject<string>();
  ngOnInit() {
    this.Tree = this.myTree;
  }

  myTree  = [
    { name: "parent1", subnodes: [{ name: "parent1_child1", subnodes: [{ name: "parent_child1_child1", subnodes: [] }] },{ name: 'parent1_child2', subnodes: [] }]  },
      {
          name: "secondparent2",
          subnodes: [
            { name: "secondparent2_child1", subnodes: [] }
          ]
      },
        {
          name: "thirdparent3",
          subnodes: [
              {
              name: "Chandigarh3",
                  subnodes: [
                    { name: "parent3_child1_child1", subnodes: [] }
                  ]
              }
          ]
      }
  ];

  filter(name: string):any {

    this.Tree = this.myTree.filter(data => data.name.match(name) || (data.subnodes.filter(subnode => (subnode.name.match(name))).length > 0) ? true:false);

  }

  search(input: string, data: any): boolean {
   let output= data.subnodes.filter(subdata => (subdata.name.match(name)))
   if (output != undefined && output.length > 0) {
     return true;
   }
   else {
     return false;
   }

    }

  }


--**app.component.html**
<h1>Tree as UL</h1>
<tree-view [treeData]="Tree"></tree-view>
<input   type="text"  (keyup)="filter($event.target.value)"  />

我能够过滤第一个父节点和相应的子节点,但之后如何过滤子节点? 我已经编写了搜索功能,所以我可以通过传递输入和树从过滤方法调用搜索方法,我想递归地使用搜索方法

1 个答案:

答案 0 :(得分:1)

这与Angular没有任何关系,但是使用纯Javascript我设法编写了这个使用尾递归并完成工作的代码:

function walkNodes(nodes, term) {
    let hasValue = false;

    nodes.forEach(node => {
        if (searchTree(node, term)) {
        hasValue = true; 
        return;
      };
    });

    return hasValue;
  }

  function searchTree(tree, term) {
    if (tree.name === term) { return true; }

    if ((tree.subnodes && tree.subnodes.length)) {
      return walkNodes(tree.subnodes, term);
    } 

    return false;
  }

  console.log(walkNodes(myTree, 'parent1_child2')); // true
  console.log(walkNodes(myTree, 'secondparent2_child1')); // true
  console.log(walkNodes(myTree, 'secondparent2_child12')); // false

https://jsfiddle.net/efdou6q1/