Search code examples
angular-cliangular-routing

how to generate a lazy loading module using angular cli


I have an existing angular cli application and I want to add a new module to my application which will be loaded lazily

I know angular cli provides command to generate modules which can be lazily loaded, what is the quick command I need to type to do below thing

  • Generate a new module
  • Generate default component to be loaded lazily
  • Generate routing module for it and add default component to be loaded first
  • Add routing for the lazy load module in main module

When I try ng generate module module-name --route=app --routing=true, it gives me below error

Module option required when creating a lazy loaded routing module.


Solution

  • Command:

    ng generate module new-module-name --module parent-module --routing true --route path-string
    
    • ng generate module module-name: It will generate a module with name new-module-name.
    • --module parent-module: The newly created module will be added into the parent module which is app module in most of the time.
    • --routing true: Generate routing and a default component to be lazily loaded
    • --route path-string: path-string will be added as a router in the parent-module routing config.

    you will see the angular-cli output as

    CREATE src/app/modules/module-name/module-name-routing.module.ts (373 bytes) CREATE src/app/modules/module-name/module-name.module.ts (400 bytes) CREATE src/app/modules/module-name/module-name.component.scss (0 bytes) CREATE src/app/modules/module-name/module-name.component.html (29 bytes) CREATE src/app/modules/module-name/module-name.component.spec.ts (678 bytes) CREATE src/app/modules/module-name/module-name.component.ts (301 bytes) UPDATE src/app/app-routing.module.ts (1398 bytes) Done