Angular2: Retrieve data property from Angular2 routes


Quick hack to retrieve data value from routes is by using NavigationEnd event. Example below is to show page header or breadcrumb title by using data attribute on angular2 routes, we setup title property within data attribute on route and then access title value in main component which serve as main layout component of application.

Angular2 Routes Config:

    imports: [
                path: 'foo',
                component: FooComponent,
                pathMatch: 'full',
                data: { title: 'Foo' }
                path: 'tweet',
                component: BarComponent,
                pathMatch: 'full',
                data: { title: 'Bar' }
    exports: [

Component retrieving data property:

import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';

    selector: 'my-app',
    templateUrl: './app/app.component.html'

export class AppComponent implements OnInit{
    pageTitle: string;

    constructor(private router: Router) {

    ngOnInit() {
            .filter((event: any) => event instanceof NavigationEnd)
            .subscribe(() => {
                var root = this.router.routerState.snapshot.root;
                while (root) {
                    if (root.children && root.children.length) {
                        root = root.children[0];
                    } else if ( &&["title"]) {
                        this.pageTitle =["title"];
                    } else {

One thought on “Angular2: Retrieve data property from Angular2 routes

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s