2

I'm using the angular-tree-component (https://angular2-tree.readme.io/) . I would like to implement the filter functionality but from the documentation it's not really clear to me how to start using the filtering in Angular (4).

If you have

<tree-root id="tree" [focused]="true" [nodes]="nodes" [options]="options"></tree-root>

and you want to do filtering by string as on the documentation page:

tree.treeModel.filterNodes("text", true);

I would like to know how to access the tree-root from my component and then execute the filterNodes().

1 Answer 1

4

You can expose the component as a @ViewChild and access it inside your component.

<tree-root #tree [nodes]="nodes"></tree-root>

In your component do:

@ViewChild('tree') treeComponent: TreeComponent;

And finally, execute the search on the component by calling filterNodes:

treeComponent.treeModel.filterNodes("text", true);

Full example:

@Component({
  selector: 'app-root',
  template: `<div style="text-align:center">
              <br/>
              <input [(ngModel)]="filter">
              <button (click)="filterTree()">Filter</button>
              <tree-root #tree [nodes]="nodes"></tree-root>
            </div>
  `,
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  @ViewChild('tree') treeComponent: TreeComponent;

  filter = '';

  nodes = [
    {
      id: 1,
      name: 'root1',
      children: [
        { id: 2, name: 'child1' },
        { id: 3, name: 'child2' }
      ]
    },
    {
      id: 4,
      name: 'root2',
      children: [
        { id: 5, name: 'child2.1' },
        {
          id: 6,
          name: 'child2.2',
          children: [
            { id: 7, name: 'subsub' }
          ]
        }
      ]
    }
  ];

  filterTree() {
    this.treeComponent.treeModel.filterNodes(this.filter);
  }
}

See more here: How to invoke methods

Sign up to request clarification or add additional context in comments.

1 Comment

Works very well! Thank you very much. Indeed the page for the TreeModel also provides some good information to do this, I did not check this page before.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.