Can I catch a event emitted from a leaf component only in the root component? I didn't find any information about this.
Asked
Active
Viewed 362 times
1

Nicu
- 3,476
- 4
- 23
- 43
1 Answers
1
In fact, you can only be notified on a custom event from a child component in the parent component.
To implement your use case, you need to implement a shared service that you specify into your root component in its providers
attribute. This way it will be shared with this component and all the graph of its children.
This service contains an observable / subject. When a leaf wants to trigger an event, it will leverage the observer associated with this observable or the subject. The root component subscribes on this observable / subject to be notified
Here is a sample implementation. First the service:
export class EventService {
subject$: Subject<any> = new Subject();
}
Root component:
@Component({
(...)
providers: [ EventService ]
(...)
})
export class RootComponent {
constructor(private service:EventService) {
this.eventService.subject$.subscribe(event => {
// Execute when the event is received from leaf component
});
}
}
Leaf component:
@Component({
(...)
template: `
<div (click)="emitEventToRoot()">Emit event</div>
`
})
export class LeafComponent {
constructor(private service:EventService) {
}
emitEventToRoot() {
// Send the event to the root component
this.eventService.subject$.emit('some event');
}
}
These links could interest you:

Community
- 1
- 1

Thierry Templier
- 198,364
- 44
- 396
- 360