An open API service indexing awesome lists of open source software.

https://github.com/gdfreitasdev/angular-modules-lazy-loading-sample

Angular sample for lazy loading routed components
https://github.com/gdfreitasdev/angular-modules-lazy-loading-sample

angular lazy-loading

Last synced: about 1 month ago
JSON representation

Angular sample for lazy loading routed components

Awesome Lists containing this project

README

          

# angular-modules-lazy-loading-sample

Setup lazy loading for routed components

## Step by step

### Create new feature modules

Create Customer module using CLI

```
ng generate module customers --route customers --module app.module
```

Create Orders module using CLI

```
ng generate module orders --route orders --module app.module
```

The commands above will auto register routes like below, with `loadChildren` implementation using native ESM dynamic imports syntax.

```ts
const routes: Routes = [
{
path: 'customers',
loadChildren: () => import('./customers/customers.module').then(m => m.CustomersModule)
},
{
path: 'orders',
loadChildren: () => import('./orders/orders.module').then(m => m.OrdersModule)
},
{
path: '',
redirectTo: '',
pathMatch: 'full'
}
];
```

### Add router links

```html


{{title}}

Customers
Orders
Home

```

### Checkout lazy load in action

```
ng serve
```

or

```
yarn start
```

Checkout it's behaviour by navigating on http://localhost:4200

Notice JavaScript chunks being fetched while routing by looking into network inspection of browser's devtools. It also contains components styles that will be injected in the DOM.

### Bonus: Pre-loading strategy

You can also configure to automatically pre load modules to improve user experience by setting the strategy on routing module. This prevent users to have to wait for files to be downloaded when routed.

```ts
import { PreloadAllModules } from '@angular/router';

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

## References

- [Lazy-loading feature modules](https://angular.io/guide/lazy-loading-ngmodules)