VSO
VSO

Reputation: 12656

How do I set up Basic Routing in Angular 2?

I am trying to understand how very basic routing works in Angular 2 from the docs and I don't get it.

I set up a PLUNK where I have a navbar. The goal is to have the 'About' button take the user to the about component. The components are already in the plunk.

I initially wrote more here, but it comes down to the fact that I don't understand why my routing doesn't work (I feel like I set it up correctly):

<a routerLink="/home-page" routerLinkActive="active">Home</a>  

That code doesn't do anything when clicked. My route definitions look like this:

import { Routes } from '@angular/router';
import { AboutPage } from './about-page.component.ts'
import { HomePage } from './home-page.component.ts'

export const appRoutes: Routes = [
  { path: 'home-page', component: HomePage },
  { path: 'about-page', component: AboutPage }
];

Also, for whatever reason, putting <router-outlet></router-outlet> in navbar.components.ts shows router-outlet as not found and throws. Also, I am 99% percent sure that base href is set up correctly, so probably no need to check that.

In short, how do I make my routes work?

Upvotes: 0

Views: 202

Answers (1)

micronyks
micronyks

Reputation: 55443

1) added all .ts files into src folder


2) You need to import RouterModule and then use it with forRoot() method as shown in app.routing.ts

import { Routes,RouterModule } from '@angular/router';
export const routing = RouterModule.forRoot(appRoutes);


3) Now, you need to import routing in @NgModule's imports metadata.

@NgModule({
  imports: [ BrowserModule,routing ],
  ...
})


4) Last, added default route in app.routing.ts

export const appRoutes: Routes = [
     {path:'',redirectTo:'home-page',pathMatch: 'full'},
     ...
     ...
   ];


Working Demo : http://plnkr.co/edit/mEvR1vU8EEkctNikaNAi?p=preview

Upvotes: 1

Related Questions