DongBin Kim
DongBin Kim

Reputation: 1889

Is there a way to detect when the component gets detached from the DOM tree in Angular?

Say, there are two components A and B and both are subscribing an observable obs$. I dynamically load them by clicking over the tab and when one component is loaded through the click, I detach the other one. The problem is that since the detached component is still alive, it keeps subscribing the obs$ and it results in unexpected behaviour. Some may suggest to remove the component instead but that's not what I want. I want it to stay alive and just filter the stream obs$ if it's detached from the view.

Small snippet:

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

Any insight would be appreciated!

Upvotes: 0

Views: 812

Answers (1)

user4676340
user4676340

Reputation:

Since you only detach the component in the tab click function, all you have to do is

  • Store a boolean indicating if the component is detached,
  • Use that boolean to filter the observable.

You can do all of this in the tabClick function, you don't really need to have a hook on the detaching event to do that.

Upvotes: 1

Related Questions