How to make only a component as lazy loading with routing in angular within a module

Viewed 22

How to make only a component as lazy loading with routing within module but module has 4 components and one component should be lazy with routing in angular

1 Answers

You can lazy load a single component from its parent using import() like this

constructor(private vcref: ViewContainerRef, private cfr: ComponentFactoryResolver){ }

async loadGreetComponent(){
    
    this.vcref.clear();
    const { GreetComponent } = await import('./greet.component');
    let greetcomp = this.vcref.createComponent(
      this.cfr.resolveComponentFactory(GreetComponent)
    );
  
  }

Read this article for a complete explanation

Another way to do it would be to move the component to a different module and lazy load this module only. Something like this:

const routes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'about', component: AboutComponent },
  { path: 'lazy-load-me', loadChildren: () => 
    import('./lazyload/lazyload.module')
      .then(m => m.LazyloadModule) 
  },

Related