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

I created a module using the angular CLI and forgot to add -routing when I created it, now I want to add a routing module to it.

ng init --routing won't help in angular version 1.1.1 CLI

+37
angular angular-cli
source share
2 answers

This is not a problem at all.

Just add routing manually.

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

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

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

It is very small that I copy this 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 { } 

{path: '', children:[]} is just a placeholder that you have to replace (I know, because I added it to the source code). It simply ensures that the router will not complain about the <router-outlet> when you have no routes.

So, back to the question, what to do? Or copy the file into your project so that it looks exactly the same as the original CLI and add the AppRoutingModule to your imports AppModule ...

Or just add RouterModule.forRoot([/* routes here */]) instead of imports your AppModule . This will still work, with built-in support for deferred loading, and everything else works just fine.

PS

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

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

     // import { ... } from '...'; 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 necessary (e.g. app.component.html )

A source

+13
source share

All Articles