0

In my angular2 project i have implemented angular tree component.i am using the following json data

nodes = [
{
  id: 1,
  name: 'root1',
  isExpanded: true,
  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' }
      ]
    }
  ]
}
];

And my html template is,

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

getNodeName()
{
//display selected node name
 console.log();
}

Tree displaying in my tree,but my problem is, how can i get clicked node details. i want to print selected node name inside the getNodeName() function.

5
  • 1
    What are clicked node details? Where do you want to get the from? What have you tried? What is the problem? Commented Mar 10, 2017 at 5:52
  • node details are id and name. For example, when i click on root2 node i want to get id:4 and name: root2. Commented Mar 10, 2017 at 5:57
  • Please provide more code. Where do you want to get the details? Commented Mar 10, 2017 at 5:59
  • click on what node? Commented Mar 14, 2017 at 8:52
  • i need root and children nodes. Commented Mar 14, 2017 at 9:06

2 Answers 2

1

You need to handle event on each node of tree and fire it.
On <tree root> component:
@Output() clickNode = new EventEmitter<Node>(); // with Node is class of data for node.

in template:
...
<your-tree-item (click)="clickHandler(node)"></your-tree-item>
...
clickHandler(node: Node){
this.clickNode.emit(node)
}

Using your tree:
<tree-root (clickNode)="yourHandler($event)"></tree-root>

yourHandler(node: Node) { alert(node.id) }

I also writing a virtual tree component for angular 2+. And it also support your case. You can find at: https://github.com/NamNgKh/angular2_virtual_tree

I going to make CSS theme for it. so other can easily change style of it.

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

Comments

1

If you use "angular-tree-component", this will get the name of your node. Then you could improve it:

in your .html:

<tree-root [nodes]="nodes" [options]="options" (click)="clickHandler($event)"></tree-root>

in your .ts:

clickHandler(event: any) {
    if (event && event.target && event.target.childNodes[0]) {
        console.log(event.target.childNodes[0].data)
    }
}

Comments

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.