I've been playing with angular components and I came with the situation where I have multiple nested components, let's say 4 levels like RootComponent->GranParentComponent->ParentComponent->ChildComponent. I need call some service in the RootComponent with data coming from the ChildComponent, when I made changes on the ChildComponent. I've created EventEmiters through the components and it works, but the question is Can I do this without passing all the way through the components to communicate with the RootComponent. Thanks in advance.
1 Answer
Angular doesn't support event bubbling. If event bubbling is important to your application, don’t use EventEmitter; use native DOM events, instead. In your ChildComponent do something like this:
constructor(element: ElementRef){}
...
this.element.nativeElement
.dispatchEvent(new CustomEvent('myCustomEvent', {foo:bar}));
In your RootComponent:
<div (myCustomEvent)= doSomething($event)>
<GrandParentComponent ></GrandParentComponent>
</div>
3 Comments
CREM
This is OK firing the event from ChildComponent and executing some function on RootComponent, but how to pass the object with the data. I've created an example code to illustrate on stackblitz.com/edit/…
Yakov Fain
You need to use the detail property of CustomEvent. Updated your sample stackblitz.com/edit/angular-56wcbh?file=app%2Fapp.component.ts Open the browser console to see the output from the app component.
CREM
Works ok (+1) to answer