0

What's the best way of outputting a page title depending on your route path in angular2 rather than hard-coding the title, I want to output a title in the controller instead.

If user go to /dashboard and the dashboard page will have Dashboard title:

{ path: 'dashboard', component: dashComponent}

Somewhere along:

if(path==dashboard){
   title:string = "Dashboard"
} else if(path==something){
   title:string = "Something"
}

HTML Output:

<h1>{{title}}</h1

this logic works but repeating location.path seems a little bit tedious

if(this.location.path() == '/order-ahead'){
        console.log('Dashboard')
        this.title = 'Dashboard';
    } else {
        console.log('its something else');
        this.title = 'Something Else'
    }
nCore
  • 2,027
  • 7
  • 29
  • 57

3 Answers3

0

I guess, you should use more complicated logic to achieve more sophisticated solution. For example, using CanActivated guard, something like in this ticket: Angular 2 RC4 Router get intended route before activated

Community
  • 1
  • 1
Oleg Barinov
  • 1,635
  • 12
  • 7
  • isn't there a simple way? I'm only going to output page titles depending on the url route. – nCore Jul 26 '16 at 15:16
0

I think you can follow the guidance in the docs to set the title via the Title service:

import { Title } from '@angular/platform-browser';

bootstrap(AppComponent, [ Title ])

then in your component that has access to the route use something like this:

export class AppComponent {
  public constructor(private titleService: Title ) { }

  public setTitle( newTitle: string) {
    this.titleService.setTitle( newTitle );
  }
}

Here's a link to the docs on this: https://angular.io/docs/ts/latest/cookbook/set-document-title.html

Sam Storie
  • 4,444
  • 4
  • 48
  • 74
  • but that's setting the html , I'm using <a> navigate around. I know in angular1 you can get away with $location.path() == 'url'.</a> – nCore Jul 26 '16 at 15:12
  • Ahh, sorry I misunderstood what you were after. – Sam Storie Jul 26 '16 at 15:24
  • That's okay, I've edited my original post I can use location.path every if statement but that's hardcoding the path and repeating the process everytime to check the path. – nCore Jul 26 '16 at 15:33
0

Easiest solution, subscribe to route changes in the router (example for beta 3.0-2 of router):

import { Router, Event, NavigationEnd } from '@angular/router';

constructor(protected router: Router)
    {
        this.router.events.subscribe(this.routeChanges.bind(this));
    }

    protected routeChanges(event: Event)
    {
        if (event instanceof NavigationEnd) {
            let url = event.url;
        }
    }
Nilz11
  • 1,242
  • 14
  • 16