Angular2发出事件到DOM树 [英] Angular2 emit event up to the DOM tree
问题描述
我有3个组件来管理一棵树:面板,树和节点
I have 3 Components to manage a tree: Panel, Tree and Node.
面板包含一个树
@Component({
selector: 'panel',
template: `
<input type="button" (click)="createNode()" value="new node">
<input type="button" (click)="createChild()" value="new child">
<input type="button" (click)="deleteNode()" value="delete node">
<tree [tree]="myTree"></tree>
Selected node: {{selectedNode | json}}
`,
directives: [Tree]
})
export class Panel {
public selectedNode;
constructor() {}
}
树包含一个或多个节点(根节点)
Tree contains one or more Nodes (root nodes)
@Component({
selector: 'tree',
template: `<node *ngFor="#n of tree" [node]="n"></node>`,
directives: [Node]
})
export class Tree {
@Input() tree;
constructor() {}
}
和在第一个弯道的节点可以包含一个或多个节点(子节点)
and one Node in turn could contain one or more Nodes (child nodes)
@Component({
selector: 'node',
providers: [],
template: `
<p (click)="onSelect(node)">{{node.name}}</p>
<div class="subTree">
<node *ngFor="#n of node.children" [node]="n"></node>
</div>
`,
directives: [Node]
})
export class Node {
@Input() node;
constructor() {}
onSelect(node) {
console.log("Selected node: " + node.name);
}
}
面板是一个组件,它允许通过添加和删除节点树编辑树。
我正在试图做的是更新变量selectedNode面板内点击我在树中的节点每次。
Panel is a Component that allows to edit the Tree by adding and removing Node to the Tree. What I'm trying to do is update a variable "selectedNode" inside Panel every time I click on a Node in the Tree.
单击事件的处理程序是节点组件中,在这里我想告诉一个节点被点击面板,然后更新上述变量。
The handler of the click event is inside the Node component, here I would like to inform the Panel that a Node is clicked and then update the above variable.
下面是一个简化的我做了什么Plunkr 至今
我在几个可能的解决方案调查没有发现任何适合我的需要。我知道@输出,EventEmitter机制允许将事件发送到父组件,但在我的情况下的上级是树(根节点的情况下)或者其他节点(子节点)。
I investigated on several possible solutions without finding anything that fits my needs. I know @Output-EventEmitter mechanism allows to send an event to the parent component, but in my case the parent of the Node is the Tree (in case of root nodes) or another Node (child nodes).
在我使用AngularJS $发出
被点击节点和 $关于
来抓住它时发送事件在面板和更新selectedNode变量。
在Angular2的 $发出
$广播
$关于
事件机制没有更多可用的。
我怎样才能达到我的目标是什么?任何建议,即使是基于事件的,是AP preciated。
In AngularJS I used $emit
to send an event when a Node was clicked and $on
to catch it in Panel and update the selectedNode variable.
In Angular2 the $emit
$broadcast
$on
event mechanism is no more available.
How can I reach my goal? Any suggestion, even not event-based, is appreciated.
推荐答案
按 EventEmitter
解雇事件没有泡沫的。一种解决方法是使用 EventBus
服务,而不是
Events fired by EventEmitter
don't bubble at all. A workaround is to use an EventBus
service instead.
又见<一个href=\"http://stackoverflow.com/questions/34700438/global-events-in-angular-2/34700475#34700475\">Global在角2 和事件<一个href=\"http://stackoverflow.com/questions/34376854/delegation-eventemitter-in-angular2/34402436#34402436\">Delegation: EventEmitter在Angular2
这篇关于Angular2发出事件到DOM树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!