jona jürgen
jona jürgen

Reputation: 1839

Angular2 ngOnDestroy, emit event

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);
}

Upvotes: 11

Views: 20612

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202216

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

Upvotes: 17

Related Questions