Reputation: 727
I've implemented lazy loading on my angular app but if I switch pages, the previously loaded page go back to pristine state(ngOnInit being triggered again)
{ path: '/posts', loadChildren: () => import('./posts/main.module').then(m => m.MainModule) }
Upvotes: 1
Views: 2955
Reputation: 1847
That behavior has nothing to do with lazy loading.
Whenever a component is not used in the DOM anymore, Angular starts the clean up process. Therefor it executes the "ngOnDestroy" Method of a component (if there is any). After this chance for a component to do cleanups (or save data), the component gets destroyed.
Therefor, when the same component is added to the DOM again, then its a new instance and "ngOnInit" gets executed again.
You can try this with a simple "*ngIf". Because the ngIf will remove and add a component from the DOM depending on the if-statement.
If you are using a "hide", then the component will not be shown, but will still be part of the DOM, therefor the instance remains the same.
In your case, the component gets placed and removed by the router...
Upvotes: 2