Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: How to access ActivatedRoute snapshot data from another component

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 ?

like image 482
Hristo Eftimov Avatar asked Feb 22 '17 17:02

Hristo Eftimov


People also ask

What is ActivatedRoute snapshot data?

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.


1 Answers

  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

like image 97
Günter Zöchbauer Avatar answered Oct 20 '22 00:10

Günter Zöchbauer