1

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 1

2

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>
Sign up to request clarification or add additional context in comments.

3 Comments

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/…
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.
Works ok (+1) to answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.