Angular2 ngOnDestroy, emit event

Can I issue my own event on ngOnDestroy? I tried, but it does not seem to work ... I basically need to know when the Directive is removed from the user interface.

@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); } 
+6
source share
1 answer

I think you could use an EventEmitter defined in the service and not inside the component itself. This way, your component will use this service attribute to retrieve 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 may subscribe to this EventEmitter for notification:

 this.service.onDestroyEvent.subscribe(data => { ... }); 

Hope this helps you, Thierry

+10
source

All Articles