Last active
June 24, 2016 18:57
-
-
Save sweeneyrobb/d2154bbd34a416642767c00f085442a5 to your computer and use it in GitHub Desktop.
Angular 2 Router Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { ContactsListComponent } from './contacts-list.component'; | |
import { ContactsDetailComponent } from './contacts-detail.component'; | |
import { WelcomeComponent } from './welcome.component'; | |
export const AppRoutes = [ | |
{ | |
name: "Welcome", | |
description: "Welcome to the Contacts Application.", | |
path: '', | |
showInNav: true, | |
component: WelcomeComponent | |
}, { | |
name: "List", | |
description: "List of your contacts.", | |
path: 'contacts', | |
showInNav: true, | |
component: ContactsListComponent | |
}, { | |
name: "Details", | |
description: "Details for your contact.", | |
path: 'contact/:id', | |
showInNav: false, | |
component: ContactsDetailComponent | |
} | |
] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component, OnInit } from '@angular/core' | |
import { Router, RoutesRecognized, ActivatedRouteSnapshot } from '@angular/router' | |
import { AppRoutes } from './app-routes' | |
import 'rxjs/add/operator/map' | |
import 'rxjs/add/operator/filter' | |
@Component({ | |
selector: 'my-header', | |
template: ` | |
<div *ngIf="routeData" class="jumbotron"> | |
<h1>{{ routeData.name }}</h1> | |
<p>{{ routeData.description }}</p> | |
</div>` | |
}) | |
export class HeaderComponent implements OnInit { | |
constructor( | |
private router: Router | |
) { } | |
routeData : any = null | |
ngOnInit() { | |
this.router.events | |
.filter(e => e instanceof RoutesRecognized) | |
.map(e => <RoutesRecognized>e) | |
.subscribe((e) => { | |
const currentPath = e.state.firstChild(e.state.root)._routeConfig.path | |
this.routeData = AppRoutes.find(route => route.path === currentPath) | |
}) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { bootstrap } from '@angular/platform-browser-dynamic'; | |
import { AppComponent } from './app.component'; | |
import { provideRouter } from '@angular/router'; | |
import { AppRoutes } from './app-routes'; | |
bootstrap(AppComponent, [provideRouter(AppRoutes)]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment