如何为每个角树根节点的子节点指定链接或函数?

时间:2017-10-06 08:11:50

标签: html angular typescript tree nodes

如何为每个角树根节点的子节点指定链接或函数?

.html的例子

<!-- edited after advise from @SachilaRanawaka, 
 somehow (onToggle) is not having any reactions
 but (click) has-->

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

.ts的例子

nodes = [{id:1,name:"parent",children:[{id:2,name:"children1"},
                                       {id:3,name:"children2"}]
        }];

// edited after advise from @SachilaRanawaka
handleEvent(event){
   alert(event.eventName);
}

如何指定链接(例如 a href 路由器?)或在点击children1或children2时运行的功能?

有遗产吗?

有关这方面的内容:

nodes = [{id:1,name:"parent",children:[
                                 {id:2,name:"children1", link:"/test/children1.html" },                                           
                                 {id:3,name:"children2", link:"/test/children2.html" }
                             ]
         }];

以下是我正在使用的树种类的链接:Angular 2 Tree

1 个答案:

答案 0 :(得分:0)

好的,我找到了上述问题的解决方案。

所以只是分享。这就是......

这样做的想法是获取没有子节点的节点的名称并使用它做一些事情。使其可点击。

通常,可点击节点应该是最后一个展开的节点。

对于我下面的示例,我给它一个函数来调用带有节点名称的警报。

更新.HTML以使用ng-template

<tree-root #tree [nodes]="nodes">
 <ng-template #treeNodeTemplate let-node>
   <!--For node with no children(last node), give it a function/link-->
   <div *ngIf="!node.data.children">
     <span (click)="doSomething(node.data.name)">{{ node.data.name }}</span>
   </div>
   <!--For node with children, don't need a link, all it needs to do is to just expand-->
   <div *ngIf="node.data.children">
     <span>{{ node.data.name }}</span>
   </div>
 </ng-template>
</tree-root>

将doSomething(name)方法添加到.ts

    nodes = [{id:1,name:"parent",children:[
                                     {id:2,name:"children1"},                                           
                                     {id:3,name:"children2"}
                                 ]
             }];

    doSomething(nodeName){
       alert(nodeName);
    }

所以输出:

 > parent               <--- not clickable
    > children1        <--- clickable and generated alert box
    > children2        <--- clickable and generated alert box