繁体   English   中英

Angular2 ngOnDestroy,发出事件

[英]Angular2 ngOnDestroy, emit event

是否可以在ngOnDestroy上发出自定义事件? 我试过,但似乎它不起作用......我基本上需要知道从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);
}

我认为您可以使用服务中定义的EventEmitter而不是组件本身。 这样,您的组件将利用服务的此属性来发出事件。

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

其他元素/组件可以在此EventEmitter上订阅以通知:

this.service.onDestroyEvent.subscribe(data => { ... });

希望它对你有帮助,蒂埃里

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM