Angular 2 Router
Page and Routing
Angular 2 has routing feature same as Angular 1.
Different URL uses different page template.
In this example, use following url and create page template
URL | Template, Component |
---|---|
/ | Redirect /home |
/home | App2Component |
/detail | DetailComponent |
This entry is series from Angular 2 GetStarted. Other source files are there.
main.ts doesn’t have change at all.
app.module.ts
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { App2Component } from './app2.component'; import { SubComponent } from './sub.component'; import { DetailComponent } from "./detail.component"; @NgModule({ imports: [ BrowserModule, AppRoutingModule ], declarations: [ AppComponent, App2Component, SubComponent, DetailComponent ], bootstrap: [ AppComponent ] }) export class AppModule { }
Import all Components and, Routing Module
Routing module defines routes.
Routing Module(app-routing.module.ts)
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { AppComponent } from "./app.component"; import { App2Component } from "./app2.component"; import { DetailComponent } from "./detail.component"; const routes: Routes = [ { path: '', redirectTo: '/home', pathMatch: 'full'}, { path: 'home', component: App2Component }, { path: 'detail', component: DetailComponent } ]; @NgModule({ imports: [ RouterModule.forRoot(routes) ], exports: [ RouterModule ] }) export class AppRoutingModule {}
All route defines are in Routes
/home, /detail, and / redirects to home
AppComponent(app-component.ts)
This also includes routing. From previous section, Routes doesn’t have this definition.
But, working with router, we need router-outlet
import { Component } from '@angular/core'; @Component({ selector: 'app', template: ` <router-outlet></router-outlet> ` }) export class AppComponent { title = "Home"; }
Results
All sources ware done.
Please access following URL
- localhost:3000
- localhost:3000/home
- localhost:3000/detail
localhost:3000 redirect to /home.