我有一个组件,我在数据加载时作为占位符添加。数据加载完成后,它会用实际数据覆盖该组件。不幸的是,这个组件ngOnDestroy()方法永远不会被调用,所以它只是在后台运行并且永远不会被移除。我如何确保在被移除时捕获它并妥善处置它?下面的代码:如何捕获onDestroy在Angular2中被删除的组件
template.html
<div class="row status">
<div class="small-6 columns indent">SOME DATA</div>
<div id='data_id' class="small-6 columns">
<!-- This is the component that will be removed and replaced -->
<app-loading-dots></app-loading-dots>
</div>
</div>
component_remover.ts
update_view(new_data, selector): void {
var text_element = d3.select(selector);
this.tween_it(text_element, new_data, 5000);
}
搬入dots.ts
export class LoadingDotsComponent implements OnInit, OnDestroy {
/* Other code... */
constructor() {}
ngOnDestroy() {
console.log("Destroyed");
clearInterval(this.interval);
}
/* ... */
}
基本上,component_remover接受新数据(这是一个数字),并将它从0补间到新数字,然后将新文本写入text_element。这会覆盖我的模板中的我的app_loading_dots组件,但我不会捕获ngOnDestroy调用。任何想法如何妥善处置?
除了@GuilhermeMeireles的建议,您可能可以在覆盖数据之前自行调用OnDestroy函数。 查看http://stackoverflow.com/questions/34093670/angular-2-adding-removing-components-on-the-fly想法如何 – Gab
感谢您的评论!我想我要使用* ngIf – AMB0027