有没有一种方法可以检测组件何时从Angular的DOM树中分离出来?

时间:2019-06-17 05:38:39

标签: angular

说,有两个成分AB,并且都在订阅可观察的obs$。我通过单击选项卡来动态加载它们,并且当通过单击加载一个组件时,我将分离另一个组件。问题在于,由于分离的组件仍然有效,因此它继续订阅obs$并导致意外的行为。有些人可能建议删除该组件,但这不是我想要的。我希望它保持生命,并且如果流obs$与视图分离,请对其进行过滤

小片段:

// load/detach/insert side
export class DynamicallyLoadComponent {
  @ViewChild('container', {read: ViewContainerRef}) container: ViewContainerRef;

  onTabClick(key: string): void {
    this.container.detach(0);

    // if component is already loaded => insert
    // else => load 
  }
}


// stream subscribing side
export class DynamicallyLoadedComponent implements OnInit {
  ngOnInit() {
    const obs$ = someStreamFromSomewhere;

    obs$.pipe(
      // Wonder if there's a way to detect to detect if the component is detached from the DOM tree
      filter(() => !isComponentDetached
    ).subscribe(() => Do What I want);
  }
}

任何见识将不胜感激!

1 个答案:

答案 0 :(得分:0)

由于只分离了选项卡单击功能中的组件,因此您要做的就是

  • 存储一个布尔值,指示组件是否已分离,
  • 使用该布尔值过滤可观察对象。

您可以在tabClick函数中完成所有这些操作,您实际上并不需要在detaching事件上钩住即可。