0

I created an external window in the Angular application, everything works fine but I want to close the external window after application logout

written the code below, I'm moving from 1 page to another page then the external window closing properly. If I press the logout button then the external window does not close (ngOnDestroy is not called in the case of application logout)

    ngAfterViewInit() {
    this.externalWindow = window.open('', '', `width=${this.wWidth},height=${this.wHeight},left=${this.wLeft},top=${this.wTop}`)

    this.host = new DomPortalOutlet(
      this.externalWindow.document.body,
      this.componentFactoryResolver,
      this.applicationRef,
      this.injector
    )

    this.host.attach(this.portal)
  }

  ngOnDestroy() {
    this.externalWindow.close()
  }
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
Arun M
  • 133
  • 1
  • 11
  • Open window button code and logout button code are in different components – Arun M Jan 27 '22 at 15:47
  • Shouldn't matter in which components they are. Maybe I understand the question wrong, you want to close the open window by pressing a button inside it? – cloned Jan 27 '22 at 16:03
  • this.externalWindow in the window component, logout implementation in the layout component. How can we call this.externalWindow.clsone() in layout component? – Arun M Jan 28 '22 at 03:48
  • Found the solution and Updated – Arun M Jan 28 '22 at 05:19

2 Answers2

0
this.externalWindow.close()

is indeed the functionality you need to use. The problem is that you need to trigger it upon logout click as well. You can have something like

onClick="closeExternalWindow()"

of course, you need to implement closeExternalWindow which does the logout for externalWindow and then call this function both on destroy and logout click.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
0

ngOnDestroy fires only when component destroys. In the logout use case, we are redirecting to the login URL which means it refreshes the page (This is outside angular workflow) hence ngOnDestroy not firing.

If I move 1 route to a different route within the application then ngOnDestroy fires and closes the external window.

This article helped me to find the solution ngOnDestroy not firing on page reload

Solution:

ngOnInit() {
  window.onbeforeunload = () => this.ngOnDestroy()
}
Arun M
  • 133
  • 1
  • 11