0

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.

Parsa
  • 79
  • 1
  • 10
  • If you add an event to a global object like window, it will listen globally, meaning even outside of the the component its been added in. Have you tried adding the event to an element inside your component or even using angulars `(click)` event? – chrnx Dec 09 '20 at 12:25
  • @chrnx Actually I had to add click listener on document or window because I wanted to close a dropdown if the user clicked outside of dropdown. Also I think it does remove the event even if it was declared on global objects, see: https://stackoverflow.com/questions/44454203/angular-renderer2-remove-listener – Parsa Dec 09 '20 at 12:45

0 Answers0