6

I'm using router.event.subscribe @angular/router to watch the url change to execute an if statement though event.subscribe works fine. But my question is how can I avoid repeating my if statement just to show the title on these urls. It's probably something else than router.subscribe but not sure what to use for this.

basically wanted a dynamic title based on the url you are on.

this._router.events.subscribe((event) => { console.log('route changed'); if(this.location.path() == '/1'){ this.title = 'Title 1'; } else if(this.location.path() == '/2'){ this.title = 'Title 2'; } }); 

I don't know if that make sense at all. I could change my route.ts paths to have something like { path: 'Title-1' }and just remove the - by doing .replace() but doing this will give me www.mysite.com/Title-1 but it doesn't look very friendly.

2 Answers 2

8

Here's my approach which works fine, especially for nested routes:

I use a recursive helper method to grab the deepest available title after a route has changed:

@Component({ selector: 'app', template: ` <h1>{{title}}</h1> <router-outlet></router-outlet> ` }) export class AppComponent implements OnInit { constructor(private router: Router) {} title: string; private getDeepestTitle(routeSnapshot: ActivatedRouteSnapshot) { var title = routeSnapshot.data ? routeSnapshot.data['title'] : ''; if (routeSnapshot.firstChild) { title = this.getDeepestTitle(routeSnapshot.firstChild) || title; } return title; } ngOnInit() { this.router.events.subscribe((event) => { if (event instanceof NavigationEnd) { this.title = this.getDeepestTitle(this.router.routerState.snapshot.root); } }); } } 

This is assuming, that you have assigned page titles within the data property of your routes, like this:

{ path: 'example', component: ExampleComponent, data: { title: 'Some Page' } } 
Sign up to request clarification or add additional context in comments.

Comments

0

Edit You can use camel case. See it used at end part of answer

this.title = camelize(lastPartOfUrl.replace(/-/g,' ')); function camelize(str) { return str.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, function(match, index) { if (+match === 0) return ""; // or if (/\s+/.test(match)) for white spaces return index == 0 ? match.toLowerCase() : match.toUpperCase(); }); } 

Answer is the using some logic/trick.

Proof with simple javascript (a must working solution)

 this._router.events.subscribe((event) => { console.log('route changed'); var url = window.location.toString(); var ar = url.split('/'); var lastPartOfUrl = ar[ar.length-1]; this.title = "Title "+lastPartOfUrl ; }); 

With angular path (only if you don't like the above simple way).. Now same logic but only if .path() is working correctly for you

 this._router.events.subscribe((event) => { console.log('route changed'); var lastPartOfUrl = this.location.path(); this.title = "Title "+lastPartOfUrl ; }); 

Edit

Above will give you Title 1. And if you really want dynamic titles then you must have to follow some pattern off course. Either you have to use if or you have to use some formula/pattern

Say your current url is http://stackoverflow.com/questions/38613960/angular2-using-router-subscribe-to-watch-url-change . You can get the best of title from that url could be like

 this._router.events.subscribe((event) => { console.log('route changed'); var lastPartOfUrl = this.location.path(); //this.title = lastPartOfUrl.replace(/-/g,' '); //following will be the result //angular2 using router subscribe to watch url change this.title = camelize(lastPartOfUrl.replace(/-/g,' ')); //Angular2 Using Router Subscribe To Watch Url Change }); 

5 Comments

I had this approach in my head as well but by doing this I will have something like title-1 or dashboard-3. Substring or regex this will be a pain as urls have different character counts. Was hoping to have "Title 1" as the end result, I guess that's why I did the if statement.
Sorry can not get you clearly. It wont give you title-1, but it is giving Title 1. subscribe-to-watch-url-change. Please see my edit at ending of answer
Thanks, no it won't give Title 1 but it now it will give me title 1. Isn't there a way to have like (Dashboard Preview Test) than (dashboard preview test). Well unless I make the path: 'Dashboard-Preview-Test' in my route.ts but that will give me www.mysite.com/Dashboard-Preview-Test in the url.
Of course there is and its simple use camel case. And i said it will give title when typed hardcocded "Title ", using regex yes it will give "title".
Now see plz edited answer. It will give you camelized title.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.