问题
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);
}
回答1:
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
来源:https://stackoverflow.com/questions/34743069/angular2-ngondestroy-emit-event