Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 9 preload only specific modules and preload other modules when required and not all at a time

 RouterModule.forRoot(routes,
    { preloadingStrategy: PreloadAllModules })

Angular's official documentation provides this preloading strategy to preload all modules. However, I don't want all of the several modules load up. I want sub-directories to preload after opening parent directory. Also, preload other possible modules which can be called from current active route. I don't want all modules to preload at start. How do I do that?

like image 457
Subhrangshu Adhikary Avatar asked Nov 03 '25 16:11

Subhrangshu Adhikary


2 Answers

You can introduce a data property with all routes to decide which modules to preload and which to not and implement PreloadAllModule and change implementation depending on this data flag.

Refer to :- https://coryrylan.com/blog/custom-preloading-and-lazy-loading-strategies-with-angular

You can have custom preloading via having some custom code in Appcomponent, not via Preload strategy. For doing so refer to :-

https://medium.com/dev-genius/advanced-preloading-strategy-for-large-applications-in-angular-cd7ac2b763af

like image 173
Aakash Garg Avatar answered Nov 06 '25 06:11

Aakash Garg


We can use custom pre-loading strategies. For example :

import { PreloadingStrategy, Route } from '@angular/router';

import { Observable, of } from 'rxjs';

export class AppCustomPreloader implements PreloadingStrategy {
  preload(route: Route, load: Function): Observable<any> {
    return route.data && route.data.preload ? load() : of(null);
  }
}

And then in the module :

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { AppCustomPreloader } from './app-routing-loader';
import { Feature1Component } from './feature-1/feature-1.component';

const routes: Routes = [
  {
    path: 'route',
    loadChildren: './example.module#ExampleModule',
    data: { preload: true } // Custom property
  }
];

@NgModule({
RouterModule.forRoot(routes, { preloadingStrategy: AppCustomPreloader })], 
exports: [RouterModule],
providers: [AppCustomPreloader]
})
like image 36
Gauri Kesava Kumar Avatar answered Nov 06 '25 07:11

Gauri Kesava Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!