If I define event listeners on global objects available in browser like document or window, then when we're on list-page component and refresh the page and after that refresh, the click event that I defined on list-page happens and after that leave the component that event listener doesn't destroy! It doesn't matter how I define my event listener(through @HostListener() or like this case, with Renderer2), the weird behavior is the same. So that console.log(1); will also logged if we're on another component other than list-page component. Note just in case, I'm using angular universal too and if I don't refresh the page in list-page.component and then that event happens and after that leave the component, that behavior won't happen!
list-page.component.ts:
constructor(private renderer: Renderer2) {
this.dropdownClickListener = this.renderer.listen('window', 'click', (e) => {
if (this.dropdownOpen) {
if (e.target !== this.dropdownBtn.nativeElement && e.target !== this.dropdown.nativeElement) {
this.dropdownOpen = false;
}
}
console.log(1);
});
}
ngOnInit() {
if (isPlatformBrowser(this.platformId)) {
this.renderOnBrowser = true;
}
}
ngOnDestroy() {
if (this.dropdownClickListener) {
this.dropdownClickListener();
}
if (isPlatformBrowser(this.platformId)) {
this.transferState.remove(STATE_KEY_LISTPAGE);
this.transferState.remove(STATE_KEY_MAINMENU);
this.mobileModeSubscription.unsubscribe();
this.currentModalTabsSubscription.unsubscribe();
}
}
list-page.component.html:
<ng-container *ngIf="renderOnBrowser && !isMobileMode">
...
</ng-container>
app.component.html:
<main class="page">
<div class="outletPlace">
<router-outlet></router-outlet>
</div>
</main>
Note: The list-page.component is direct child of my app.component.