By   January 25, 2017

Angular2 Routes:

In this post we are going to use how to use routes with Angular2 for your components. We are going to create two components and add routes for those components. Let’s first install angular-cli.

Install angular cli

Install angular cli

Let’s create a new project HelloWorld.

create project

create project

The command creates the following files:

files created

files created

The main folder structure looks like this:

main folder structure

main folder structure

The src folder looks like the following:

src folder structure

src folder structure

Let’s run the project using ng serve command:

ng serve

ng serve

And open the browser with http://localhost:4200

app works

app works

Adding Components

Let’s add components to our applications. Here we are adding two components ComponentOne and ComponentTwo.

>ng generate component ComponentOne
>ng generate component ComponentTwo


ng generate component

ng generate component

app.module.ts

Now we need to RouterModule from @angular/router. The good thing is angular-cli already adds the router when we created the project. First we need to import the RouterModule.

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

Now let’s import the two components we created above i.e. ComponentOne and ComponentTwo.

import { ComponentOneComponent } from './component-one/component-one.component';
import { ComponentTwoComponent } from './component-two/component-two.component';

Now let’s add the routes to our components.

const appRoutes : Routes = [
  { path: "componentOne", component: ComponentOneComponent},
  { path: "componentTwo", component: ComponentTwoComponent}
]

We can add the routes to the RouterModule imported above. We also need to add the imported components to declarations section to the module. Please also notice that we are adding the routes to the imports section RouterModule.forRoot(appRoutes).

@NgModule({
  declarations: [
    AppComponent,
    ComponentOneComponent,
    ComponentTwoComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    RouterModule.forRoot(appRoutes)
  ],
  providers: [],
  bootstrap: [AppComponent]
})

Let’s update the app.module.ts as follows:

app.component.html

Now we just need add where we need to decide where we need to display the components. We just need to add to app.component.html.

Running the project

Now we can run the project and see the routes in action. Let’ run it using ng serve. The main url displays the app component - http://localhost:4200/

app works main

app works main

The ComponentOne route can be used as http://localhost:4200/componentOne. Just see the contents of the components are displayed in the section where we added .

app works component one

app works component one

Here we have ComponentTwo with the url: http://localhost:4200/componentTwo

app works component two

app works component two