How to generate module with routing in angular-cli

September 25, 2022 No comments angular cli module routing

1. Generate a routing module while creating a module in angular-cli

To generate a module with routing using angular-cli use the following command:

ng generate module [module-name] --routing

or shorter:

ng g m [module-name] --routing

This command creates both module.ts and routing.module.ts together at the same in the current directory.

2. Generate a routing module with a module in sub-directory:

To create a module in sub-directory use:

ng generate module [sub-folder/module-name] --routing

or

ng g m [sub-folder/module-name] --routing

The sub-folder will be created if it does not exist.

3. Generate a module, routing for the module and component at one

There is also a way to create modules, routing, and components using single line command:

ng g m [module-name] --routing=true && ng g c [component] --skip-tests=true -m=[module-name]

For example the following command run in src/app/ directory:

ng g m pages/autocomplete --routing=true && ng g c pages/autocomplete --skip-tests=true -m=pages/autocomplete

will generate autocomplete module, routing module and component in src/app/pages/autocomplete folder:

── src
│   ├── app
│   │   └── pages
│   │       ├── autocomplete
│   │       │   ├── autocomplete.component.html
│   │       │   ├── autocomplete.component.scss
│   │       │   ├── autocomplete.component.ts
│   │       │   ├── autocomplete.module.ts
│   │       │   └── autocomplete-routing.module.ts

The AutocompleteModule has AutocompleteComponent in declarations and AutocompleteRoutingModule in imports:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { AutocompleteRoutingModule } from './autocomplete-routing.module';
import { AutocompleteComponent } from './autocomplete.component';


@NgModule({
  declarations: [
    AutocompleteComponent
  ],
  imports: [
    CommonModule,
    AutocompleteRoutingModule
  ]
})
export class AutocompleteModule { }

The newly generated AutocompleteRoutingModule is empty:

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

const routes: Routes = [];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class AutocompleteRoutingModule { }

the same as AutocompleteComponent:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-autocomplete',
  templateUrl: './autocomplete.component.html',
  styleUrls: ['./autocomplete.component.scss']
})
export class AutocompleteComponent implements OnInit {

  constructor() { }

  ngOnInit(): void {
  }

}
{{ message }}

{{ 'Comments are closed.' | trans }}