Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 638
jona jürgen Avatar asked Jan 12 '16 11:01

jona jürgen


People also ask

Why ngOnDestroy is not getting called?

ngOnDestroy doesn't get called because some components do not get destroyed when navigating to a different route.

What is ngOnDestroy ()?

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.

How angular components are destroyed?

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.


1 Answers

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

like image 136
Thierry Templier Avatar answered Sep 18 '22 09:09

Thierry Templier