0

I've this UI: enter image description here

And this is my code structure:

enter image description here

My app.routes.ts:

import { Routes } from '@angular/router';
import { HomeComponent } from './home';
import { AboutComponent } from './about';
import { NoContentComponent } from './no-content';

import { DataResolver } from './app.resolver';

export const ROUTES: Routes = [
  { path: '',      component: HomeComponent, data: { title: 'Dashboard' } },
  { path: 'home',  component: HomeComponent, data: { title: 'Home' } },
  { path: 'detail', loadChildren: './+detail#DetailModule'},
  { path: '**',    component: NoContentComponent },
];

And my sidenav.component.html has a pageTitle variable on the template, as follow:

<md-sidenav-container fullscreen>
    <md-sidenav #sidenav mode="side" class="app-sidenav">

        <menu-list #menuList></menu-list>

    </md-sidenav>

    <md-toolbar color="primary">
        <button md-icon-button (click)="sidenav.toggle()">
            <md-icon>menu</md-icon>
        </button>

        <div>{{ pageTitle }}</div>

    </md-toolbar>

    <main class="app-content">
        <router-outlet></router-outlet>
    </main>

</md-sidenav-container>

What I want to do is:

  • Grab the title from route each time a new route is fired

  • Place the title on the pageTitle sidenav.component.ts variable

Should I use a Service Events to communicate between components? What's the best and easy way to get title each time a route is fired?

Thank you in advance.

Best regards, Marcelo

1 Answer 1

1

What if you subscribe to Router.events

import { Router, ActivatedRoute, NavigationEnd } from "@angular/router";
...
constructor(
    private _router: Router ,
    private _activatedRoute: ActivatedRoute
) {}

ngOnInit() {
    this._router.events
      .filter((event) => event instanceof NavigationEnd)
      .map(() => this._activatedRoute)
      .map((route) => {
        while (route.firstChild) route = route.firstChild;
        return route;
      })
      .filter((route) => route.outlet === 'primary')
      .mergeMap((route) => route.data)
      .subscribe((event) => this.pageTitle = event['title']);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Hi. What about life cycle of the app? On my sidenav component, ngOnInit() will run only once. I can subscribe to Router.events on app.component, but here I won't be access to this.pageTitle since it's on another component.
You can subscribe to Router.events in your sidenav component too
Thanks. How stupid I was because I thought I couldn't user router evens on other components :/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.