How to load angular components by router state change?

660    Asked by Rahulverma in Python , Asked on Jan 15, 2020
Answered by Rahul verma

In Angular all components are packed in one file and loading all at once so main.bundle.js gets bigger with any new component so we can load needed components async, when the router state changes. Example of this is given below:

import { ModuleWithProviders } from '@angular/core';

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

import { EagerComponent } from './eager.component';

const routes: Routes = [

   { path: '', redirectTo: 'eager', pathMatch: 'full' },

   { path: 'eager', component: EagerComponent },

   { path: 'lazy', loadChildren: 'lazy/lazy.module#LazyModule' }

];

export const routing: ModuleWithProviders = RouterModule.forRoot(routes);


Our navigation system has only two paths: eager and lazy. To know what those paths are loading when clicking on them we need to take a look at the routing object that we passed to the root module.



Your Answer

Interviews

Parent Categories