Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bubble up angular2 custom event

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.

like image 379
Mario G. Avatar asked May 03 '16 17:05

Mario G.


2 Answers

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

like image 178
Günter Zöchbauer Avatar answered Oct 02 '22 19:10

Günter Zöchbauer


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.

like image 36
Derek Avatar answered Oct 02 '22 19:10

Derek