Angular2 ngOnDestroy, emit event

我的梦境 提交于 2019-12-03 13:27:03

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!