Angular 2 Cli adding routes to existing project
In Angular 5/6 you can use these commands to add routing to an existing project.
ng generate module app-routing --flat --module=app
--flat puts the file in src/app instead of its own folder. --module=app tells the CLI to register it in the imports array of the AppModule.
This will generate the file src/app/app-routing.module.ts
for you.
Now inside
src/app/app-routing.module.ts
you have to import the router code:import { RouterModule, Routes } from '@angular/router';
Further, edit
src/app/app-routing.module.ts
to look like this:
import { RouterModule, Routes, Router } from '@angular/router';
import {class name} from 'address your component Component';
const routes: Routes = [
{ path: '/home' , component : yourComponenetName}
];
@NgModule({
imports: [
RouterModule.forRoot(routes)
],
exports: [ RouterModule ]
})
export class AppRoutingModule { }
- Next, add the
router-outlet
tag to yourapp.html
file to tell the router where to display routed views.
<router-outlet></router-outlet>
- Additionally, you should check in an
index.html
file with this tag at the top.
<base href="/">
It will be added directly if you use the CLI command that I mention above.
I found the simplest way so far. I know this is already answered and accepted also but it is not working in the current scenarios because ng init
is removed so if you have forgotten to add routing while creating new project than you can add routes to existing project as following steps. Hope it will be helpful.
First of all add app-routing.module.ts
file in your src --> app folder
app-routing.module.ts file would be like this
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component'; // Add your component here
import { AboutComponent } from './about/about.component'; // Add your component here
//This is my case
const routes: Routes = [
{
path: '',
component: HomeComponent
},
{
path: 'about',
component: AboutComponent
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Then Import app-routing.module.ts
file in app.module.ts
file as follow.
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module'; // Added here
Now you will be able to perform routing task.
UPDATE Original question is about Angular 2 CLI. This doesn't work for curent Angular version!
Run
ng init --routing
And answer no every question from CLI. By this way you will get app-routing.module.ts.
Add
import { AppRoutingModule } from './app-routing.module';
and imports: [AppRoutingModule]
to your app.module.ts
- Profit! You get the same routing you would get if you would create routing with Angular CLI from the start.