Angular2 ngOnDestroy, emit event
Asked Answered
M

1

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);
}
Marijn answered 12/1, 2016 at 11:57 Comment(0)
A
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

Alsace answered 12/1, 2016 at 12:39 Comment(3)
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 :)Pervade
A Service is a good solution. If you need ad-hoc solution you can manually subscribe (and unsubscribe) See #37610258 for more details explanationUmpteen
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 hierarchyUnfrock

© 2022 - 2024 — McMap. All rights reserved.