11

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);
}
jona jürgen
  • 1,789
  • 4
  • 22
  • 31

1 Answers1

17

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

Mark Rajcok
  • 362,217
  • 114
  • 495
  • 492
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • Thank you very much Thierry! I have got one more question to you: I created a Service with a couple of event emitters like so: `tableViewOnInitEvent = new EventEmitter();` etc. Is it possible to set those emitters to "subscribe only / read only" ? I don't want to call the emitters directly via the service but I want to call the emitter from a function inside the Service, like this:(Inside Service): `public tableViewOnInit(tableView) { this.tableViewOnInitEvent.next({ tableView: tableView }); }` Thanks :) – jona jürgen Jan 13 '16 at 07:26
  • A Service is a good solution. If you need ad-hoc solution you can manually subscribe (and unsubscribe) See http://stackoverflow.com/questions/37609758/angular2-component-impossible-to-emit-an-output-eventemitter-inside-ngondestro?lq=1 for more details explanation – Shlomi Assaf Jul 07 '16 at 16:35
  • A notification service is a global bus, you would still need a way to filter for only the elements you care about by switching to this approach, where as an `EventEmitter` can contain its events to a hierarchy – Ruan Mendes Oct 07 '16 at 18:48