Search code examples
angularangular-routingangular-lazyloading

Angular Lazy Loaded Component Re-renders on navigation


Our application is setup so users navigating to a certain set of routes are lazy loaded like below:

{
  path: path1, 
  component: Cmp1,
  loadChildren: () => LazyLoadedModule,
}

We use a router link to navigate to one of these lazy loaded components like this...

<tile
    routerLink="path1/{{name}}/achildpath"
    [state]=someData>
    ...
</tile>

I notice when clicking on this tile the path + lazy loaded component attempts to load. The correct state is passed in initially. However, the component is destroyed immediately and then the component loads again with the state undefined! (loads without the state data but loads the correct component). The question is why is the component reloading and destroying itself on first render? Could this be a problem with the router outlet or the lazy loaded components? Our router outlet for the lazy loaded component is defined in Cmp1.


Solution

  • ngAfterViewInit is never called before getting destroyed ngAfterViewInit never gets called before destroy. OnDestroy is what gets called before destroy. But I think you mean why ngAfterViewInit never gets called before comp is destroyed. It can happen when comp is destroyed before cycle reaches there, or it's being called twice etc. https://blog.logrocket.com/angular-lifecycle-hooks/ Although without seeing rest of the code, an exact problem is just a guess for now.

    Unless tile is an component, you can't use Input/Output to transfer data like that. If it is then it's suggesed to prefix components with something like app-, then anyone else reading the code get's whats going on. @Input() decorator should be used at selector, in your case it should be something like:

    <tile [state]="someData"></tile>
    

    So regarding your main problem. You want to navigate to an component using routerLink and passing data through while doing it. Problem is you you construct component in template <tile [state]=someData></tile> this is why for the first time your component gets created and data is correctly passed though. Then you navigate user to "path1/{{name}}/achildpath" and someData does not get passed on because you are now in on a new url, someData isn't passed on because previous template that did [state]=someData no longer exists to do it. Please refer to these examples:

    https://stackblitz.com/edit/angular-pass-data-to-route-1-fhe267?file=src%2Fapp%2Fhome.component.ts

    https://www.tektutorialshub.com/angular/angular-pass-data-to-route/