Parent template:
<ul>
<tree-item [model]="tree" (addChild)="addChild($event)"></tree-item>
</ul>
Tree item template:
<li>
<div>{{model.name}}
<span [hidden]="!isFolder" (click)="addChild.emit(model)">Add Child</span>
</div>
<ul *ngFor="let m of model.children">
<tree-item [model]="m"></tree-item>
</ul>
</li>
For above example, parent receives addChild event only from the root tree-item (immediate child). Is it possible to bubble up addChild event from any tree-item? I am using angular 2.0.0-rc.0.
Events from EventEmitter
don't support bubbling.
You can either use element.dispatchEvent()
to fire a DOM event that bubbles, or use a shared service like a message bus.
See also https://angular.io/docs/ts/latest/cookbook/component-communication.html
I came here looking for a solution, and I figured out one on my own. On your tree-item
, you can add an event handler like so:
<li>
<div>{{model.name}}
<span [hidden]="!isFolder" (click)="addChild.emit(model)">Add Child</span>
</div>
<ul *ngFor="let m of model.children">
<tree-item [model]="m" (yourEventEmitter)="handleEventBubble($event)"></tree-item>
</ul>
</li>
and in your component.ts:
handleEventBubble(event): void {
this.yourEventEmitter.emit(event);
}
This will cause the event to emit on the parent element, which passes up the chain all the way up to the root element. You can even define custom bubbling logic by transforming the event before re-emitting it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With