Angular2: Retrieve data property from Angular2 routes

Standard

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:

@NgModule({
    imports: [
        RouterModule.forRoot([
            {
                path: 'foo',
                component: FooComponent,
                pathMatch: 'full',
                data: { title: 'Foo' }
            },
            {
                path: 'tweet',
                component: BarComponent,
                pathMatch: 'full',
                data: { title: 'Bar' }
            }
        ])
    ],
    exports: [
        RouterModule
    ]
})

Component retrieving data property:

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

@Component({
    selector: 'my-app',
    templateUrl: './app/app.component.html'
})

export class AppComponent implements OnInit{
    pageTitle: string;

    constructor(private router: Router) {
    }

    ngOnInit() {
        this.router.events
            .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 (root.data && root.data["title"]) {
                        this.pageTitle = root.data["title"];
                        return;
                    } else {
                        return;
                    }
                }
            });
    }
}
Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s