Change page title with angular2

Asked

Viewed 794 times

1

I am developing a site in angular2, as I do not have an in depth knowledge I am having difficulties in SEO, following the documentation I created a simple function

public constructor(private titleService: Title ) { }


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

But When I Put html

<li><a routerLink="/produtos" (click)="setTitle( 'Produtos' )>Produtos</a></li>

page is empty, would have some form to start the function when changing route?

  • 1

    Any specific reason to change the page title with a function? You can not simply set the <title> within the <head>?

  • The application is front-end so SEO needs to change the <title tag>

2 answers

1

staff I managed to solve with the following code

const routes: Routes = [{
  path: 'calendar',
  component: CalendarComponent,
  children: [
    { path: '', redirectTo: 'new', pathMatch: 'full' },
    { path: 'all', component: CalendarListComponent, data: { title: 'My Calendar' } },
    { path: 'new', component: CalendarEventComponent, data: { title: 'New Calendar Entry' } },
    { path: ':id', component: CalendarEventComponent, data: { title: 'Calendar Entry' } }
  ]
}];


import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap';

import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';
import { Title } from '@angular/platform-browser';

@Component({...})
export class AppComponent implements OnInit {
  constructor(
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private titleService: Title
  ) {}
  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.titleService.setTitle(event['title']));
  }
}

found right here in stackoverflow https://stackoverflow.com/questions/38644314/changing-the-page-title-using-the-angular-2-new-router

0

https://angular.io/api/platform-browser/Title

import {RouteConfig} from 'angular2/router';
import {Title} from 'angular2/platform/browser';

@RouteConfig([
    {path: '/home', component: HomeCmp, name: 'HomeCmp' }
])
class MyApp {
    constructor(router:Router, title:Title) {
      router.subscribe((url)=>{ //fires on every URL change
      title.setTitle(getTitleFor(url));
   });
 }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.