Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have created a module in using angular CLI and forget to add --routing while it's creation, now i want to add a routing module to it.

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

like image 210
Gourishankar Avatar asked Jul 08 '17 19:07

Gourishankar


People also ask

Can you add Angular routing later?

When we first create an Angular app with the Angular CLI using ng new , it gives us an option to add routing. Sometimes we don't know whether we want to add routing yet, so we say no. What do we do, though, if we decide to add routing later? There's no separate CLI command to set up the routing for you.


1 Answers

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.

like image 167
Meligy Avatar answered Sep 29 '22 11:09

Meligy