Emit event through nested components in Angular2
There is no support of bubbling for such events. You need to manually catch them and emit to the parent.
Another approach would be to leverage a shared service for this tree of components and use an observable / subject in it.
This way all components can subscribe on it to be notified of events even within sub sub children.
constructor(private service: SharedService) {
this.service.notifier$.subscribe(
data => {
(...)
});
}
The event will be triggered this way:
constructor(private service: SharedService) {
}
notify() {
this.service.notifier$.next('some data');
}
See this link for more details:
- https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service
If you find you have to pass certain events through make sure to be consistent and come up with a naming strategy. For instance I like to add raise
to the beginning of the method name if the only thing that method does is to re-raise an event.
eg.
(paypalTokenized)="raisePaypalTokenized($event)"
and in the ts
file:
@Output('paypalTokenized')
public paypalTokenizedEmitter = new EventEmitter<PayPalTokenizedPayload>();
// PayPal tokenized
public raisePaypalTokenized(payload: PayPalTokenizedPayload)
{
// no other logic here!
this.paypalTokenizedEmitter.emit(payload);
}
This means I can tell immediately that the event is being passed through with no further action.