Skip to content

Instantly share code, notes, and snippets.

@sweeneyrobb
Last active June 24, 2016 18:57
Show Gist options
  • Save sweeneyrobb/d2154bbd34a416642767c00f085442a5 to your computer and use it in GitHub Desktop.
Save sweeneyrobb/d2154bbd34a416642767c00f085442a5 to your computer and use it in GitHub Desktop.
Angular 2 Router Example
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
}
]
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)
})
}
}
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)]);
import { Component } from '@angular/core'
import { ROUTER_DIRECTIVES } from '@angular/router'
import { AppRoutes } from './app-routes'
@Component({
selector: 'my-nav',
template: `
<ul class="nav nav-pills nav-stacked">
<li *ngFor="let item of navItems" role="presentation" class="active"><a [routerLink]="item.path">{{item.name}}</a>
</ul>`,
directives: [ ROUTER_DIRECTIVES ]
})
export class NavComponent {
navItems = AppRoutes.filter(i => i.showInNav)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment