Attempt to use a destroyed view: detectChanges

I solved the same issue as yours, but with a much smaller code, I'll tell you the point that could help you to solve the issue.

The issue clearly comes from detectChanges() because the changes were done and the method called during the destroy phase of the component.

So you need to make your component to implements OnDestroy, then you need to cancel the changes that make this.ref.detectChanges() to be called. so your TopNavbarComponent must be similar to:

export class TopNavbarComponent implements OnDestroy {
  // ... your code

  ngOnDestroy() {
    this.cdRef.detach(); // do this

    // for me I was detecting changes using `detectChanges()` inside a subscription with `subscribe()` to observable without limitation, so was enough for me to just `unsubscribe()` like the following line;
    // this.authObserver.unsubscribe();
  }
}

P.S: Don't forget to unsubscribe() all observers that you have in your component! Anyways you have to do that, subscriptions without unsubscribing could be the main reason for hundreds of issues including this, refer to Angular/RxJs When should I unsubscribe from `Subscription`

Edit: I know other solution around in the web trying to just solve the issue by handling the error itself, while the best practice is to know the root of the issue, checking if the view destroyed or not is a good solution IMHO as the original cause could be a problem behind memory leak, who knows! so the root of the issue is that running service needs to be killed NOT just try to kill the error itself without knowing the root of the issue, for instance, running subscriptions (especially your custom one) must be closed.

So! housekeeping stuff is necessary for better performance, it is not always an easier and faster solution is the better one, if you do hide the dirt under carpets does not mean that you "cleaned" your room even if it indeed looks nice :)


Only solution that worked for me was:

if (!this.changeDetectionRef['destroyed']) {
    this.changeDetectionRef.detectChanges();
}

You can use

this.cdref.markForCheck();

instead of this.cdref.detectChanges(); in many cases. But the best approach is follow @Al-Mothafar tips