3

I have a simple microfrontend scenario that loads and embeds an angular 13 webcomponent (created with angular elements) in a container webapp. Basically, the routing works fine. When leaving the route, the ng web components gets an ngOnDestroy and is not part of the DOM anymore.

But, If I come back to this route, the angular web-component shows the last active route (seems to have some state), which does not reflect the URL browser location. If I manually reload the browser - the result is fine. It seems like the angular web-component does not get properly disconnected/destroyed when leaving the route. Is there any change to force this? So that on re-entering the route, everything look like being the first load (similar to browser refresh).

Andre Albert
  • 1,386
  • 8
  • 17
  • Have the same behavior with a large project with a wrapper application that handels the navigation and a lot of webcomponents. Our solution so far was to reset the Routerstate in the webcomponents where it happens. ```ngOnInit(): void { this.router['navigationId']=0 this.router.initialNavigation(); } ``` But i would rather find a solution that i could implement in the wrapper application once. – Sknecht Aug 31 '22 at 11:22
  • Our at least understand the problem. I dont get why this effect is happening even when NgDestroyed is called. – Sknecht Aug 31 '22 at 11:29
  • @Sknecht the explanation of this is pretty straightforward: Router is a singleton whose lifecycle is the same as the NgModule it's in: it means the Router exists as long as the script is loaded. Web components (possibly including the AppComponent) can have, on the other hand, a shorter lifecycle, being created and destroyed over time. Whereas the Router will outlive them, thus preserving its state. – yktoo Aug 07 '23 at 08:31

1 Answers1

0

I was also strugling with same behaviour, and I found two workarounds for this.

  1. Redirect to home page if location.path() is not set
export class AppComponent {
    constructor (private router: Router, private location: Location) {
        this.router.initialNavigation()
        if (!this.location.path()) {
          this.router.navigate(['']).then()
        }
      }
    }
  1. Create JumpOff page from which you will navigate to other webcomponents. When you get back to this JumpOff page/component, clear state in moment of navigation to 'home'
constructor (private readonly router: Router) {
    if (navigation_from_external_webcomponent) {
        this.router.navigate([''], { replaceUrl: true }).then()
    }
}

replaceUrl should clear the state of router. If second option is not working, try also adding:

    this.location.replaceState('')

(location is Location class, not LocationStrategy)

One more issue that I had with second option was that I had multiple calls to this component, so I needed to wrap navigation with setTimeout:

    setTimeout(() => {
        this.router.navigate([''], { replaceUrl: true }).then()
    })