is it possible to emit a custom event on ngOnDestroy ? I tried, but it seems like it does not work... I basically need to know when a Directive is removed from the UI.
@Output() rowInit = new EventEmitter();
@Output() rowDestroy = new EventEmitter();
ngAfterViewInit() {
this.rowInit.emit(this);
}
ngOnDestroy() {
console.log("I get called, but not emit :(, ngAfterViewInit works :)");
this.rowDestroy.emit(this);
}
ngOnDestroy doesn't get called because some components do not get destroyed when navigating to a different route.
ngOnDestroy() gets called when a component is about to be destroyed. Notice how the example "destroys" the child component via the conditional ngIf='showChild'. By toggling the value of showChild, Angular creates and destroys the child component each time this value changes.
To force a component to be destroyed, you use the HostListener from the Angular Core library. When using HostListener , you specify the event you want to listen to on the host of the component. In our case, we listen for the unloaded event so that when the page is unloaded, ngOnDestroy() will be triggered.
I think that you could use an EventEmitter
defined in a service instead of within the component itself. That way, your component would leverage this attribute of the service to emit the event.
import {EventEmitter} from 'angular2/core';
export class NotificationService {
onDestroyEvent: EventEmitter<string> = new EventEmitter();
constructor() {}
}
export class MyComponent implements OnDestroy {
constructor(service:NotificationService) {
this.service = service;
}
ngOnDestroy() {
this.service.onDestroyEvent.emit('component destroyed');
}
}
Other elements / components can subscribe on this EventEmitter to be notified:
this.service.onDestroyEvent.subscribe(data => { ... });
Hope it helps you, Thierry
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With