I am using the Angular2 Material Toolbar and I want to pass the current page title to it.
My app.component has a header component and the current page component:
@Component({
selector: 'mi-root',
template: `
<mi-header></mi-header>
<router-outlet></router-outlet>
`
})
export class AppComponent {
constructor() {}
}
In my app.routing I have a routing object with custom title
property:
const APP_ROUTES: Routes = [
{
path: '',
component: HomeComponent,
data: {
title: 'Home'
}
}, {
path: 'settings',
component: SettingsComponent,
data: {
title: 'Settings'
}
}
];
Now I want to access the data.title
property from my header.component but unfortunately it is undefined. My data
object is empty:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute} from '@angular/router';
@Component({
selector: 'mi-header',
template: `
<md-toolbar color="primary">
<span class="u-ml">{{title}}</span>
</md-toolbar>
`,
styles: []
})
export class HeaderComponent implements OnInit {
title: string;
constructor(private route: ActivatedRoute) {
this.title = this.route.snapshot.data['title'];
}
}
If I try to access the same property with the same way but from the HomeComponent
or SettingsComponent
it works fine:
import { Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'mi-settings',
template: `
<h1>Welcome to {{title}} screen</h1>
`,
styles: []
})
export class SettingsComponent {
title: string;
constructor(private route: ActivatedRoute) {
this.title = route.snapshot.data['title'];
}
}
So, how can I access the route.snapshot.data['title']
from my HeaderComponent
?
ActivatedRouteSnapshotlink Contains the information about a route associated with a component loaded in an outlet at a particular moment in time. ActivatedRouteSnapshot can also be used to traverse the router state tree.
constructor(router:Router, route:ActivatedRoute) {
router.events
.filter(e => e instanceof NavigationEnd)
.forEach(e => {
console.log('title', route.root.firstChild.snapshot.data.title);
}
}
Plunker example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With