How to add a routing module to an existing module in angular CLI version 1.1.1?

That's not a problem at all.

Just add the routing manually.

All that the --routing flag does, in addition to adding <router-outlet></router-outlet> in app.component.html, is add q RouterModule.forRoot() call in a separate module called AppRoutingModule, and include that module in the imports of AppModule.

So, in app.module.ts, it adds AppRoutingModule to the imports of your AppModule.

The AppRoutingModule is defined as app-routing.module.ts, which is created from this template.

It's very small that I'll copy it here:

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

const routes: Routes = [
  {
    path: '',
    children: []
  }
];

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

The {path: '', children:[]} is just a placeholder that you are expected to replace (I know because I added it to the source code). It just makes sure the router doesn't complain about the <router-outlet> when you don't have any routes.

So, back to the question, what should you do? Either copy the file to your project, to look just like the original CLI, and add AppRoutingModule to your AppModule's imports...

Or just add RouterModule.forRoot([/* routes here */]) to your AppModule's imports instead. It'll still work, with built-in support for lazy loading and everything else working just fine.

P.S.

Remember that to add child routes, you can always generate more modules with routing ng generate module Foo --routing regardless of whether you used the --routing flag with ng new or not. No configuration or any magic to worry about.


  1. ng generate module app-routing --module app --flat
    • Replace app with the name of your existing module
    • Replace app-routing with the name to give the routing module
  2. In the new module, add appRoutes and RouterModule.forRoot or RouterModule.forChild.

    import { NgModule } from '@angular/core';
    import { CommonModule } from '@angular/common';
    import { Routes, RouterModule } from '@angular/router';
    
    const appRoutes: Routes = [
        { path: 'some-path', component: SomeComponent }
    ];
    
    @NgModule({
        imports: [
            RouterModule.forRoot(appRoutes)
        ],
        exports: [
            RouterModule
        ]
    })
    export class AppRoutingModule {}
    
  3. Add <router-outlet></router-outlet> to your component if needed (e.g., app.component.html)

Source