I have an existing Angular 2 App. Now I would like to use routing for navigation. Is there a way to add routing to an existing Angular 2 Project using the Angular 2 Cli?
Lets say I have an Component "test" and want a route to this in a global Scope.
At the basic level, routing allows angular to display different "pages" or components. You probably want to have it, if you want to navigate across pages in your application. It shouldn't hurt anything if you add it, but don't use it.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With