Angular Route
Angular Route
Routing is one of big topic for Single Page Application. Other framework also supports Routing.
Create app with Route
ng new appname --routing
Create Routing file
example) app.module.ts
import { ModuleWithProviders } from '@angular/core'; import { RouterModule } from '@angular/router'; import { MainComponent } from './main.component'; import { ParamComponent } from './param.component'; import { ContentComponent } from './content.component'; import { NotfoundComponent } from './notfound.component'; import { ChildpageComponent } from './childpage.component'; import { DataComponent } from './data.component'; const Routes = [ { path: '', component: MainComponent }, { path: 'main', component: MainComponent }, { path: 'param', component: ParamComponent }, { path: 'data', component: DataComponent, data: { category: 'Angular'} }, { path: 'contents/:id', component: ContentComponent, children: [ { path: 'pages/:page', component: ChildpageComponent } ]}, { path: 'top', redirectTo: 'main', pathMatch: 'full' }, { path: '**', component: NotfoundComponent } ]; export const APP_ROUTES: ModuleWithProviders = RouterModule.forRoot(Routes);
In this case, we support following URLs
localhost:4200 localhost:4200/main localhost:4200/param localhost:4200/data localhost:4200/contents/1 localhost:4200/contents/1/pages/2 localhost:4200/top
The last ** is exception. If the user access others (not above url), redirect to NotfoundComponent
Import Routing into module file
app.module.ts
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { MainComponent } from './main.component'; import { ParamComponent } from './param.component'; import { NotfoundComponent } from './notfound.component'; import { ContentComponent } from './content.component'; import { ChildpageComponent } from './childpage.component'; import { DataComponent } from './data.component'; import { APP_ROUTES } from './app.routing'; @NgModule({ imports: [ BrowserModule, APP_ROUTES ], declarations: [ MainComponent, ParamComponent, NotfoundComponent, ContentComponent, ChildpageComponent, DataComponent, AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule {}
App Root
app.component.ts
import { Component } from '@angular/core'; import { Router } from '@angular/router'; @Component({ selector: 'app-root', template: ` <router-outlet></router-outlet> ` }) export class AppComponent { constructor(private router: Router) {} }
router-outlet is key for routing. This indicates using routing into app.