How to change page title with routing in Angular application?

浪尽此生 提交于 2020-07-31 07:26:24

问题


Is there any npm module/ other way like React-Helmet that allows us to change page title as we route through our Angular application?

PS: I am using Angular 5.


回答1:


You have a TitleService in Angular 5. Inject it in your component's constructor, and use the setTitle() method.

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

....

constructor(private titleService:Title) {
  this.titleService.setTitle("Some title");
}

Here are the docs from Angular: https://v2.angular.io/docs/ts/latest/cookbook/set-document-title.html




回答2:


This is the correct way to use

export class AppComponent implements OnInit {
  constructor(private router: Router, private titleService: Title) {
  }

  ngOnInit() {
    this.router.events
      .pipe(
        filter((event) => event instanceof NavigationEnd)
        map(() => this.router)
      )
      .subscribe((event) => {
          const title = this.getTitle(this.router.routerState, this.router.routerState.root).join(' | ');
          this.titleService.setTitle(title);
        }
      );
  }

  getTitle(state, parent) {
    const data = [];
    if (parent && parent.snapshot.data && parent.snapshot.data.title) {
      data.push(parent.snapshot.data.title);
    }

    if (state && parent) {
      data.push(... this.getTitle(state, state.firstChild(parent)));
    }
    return data;
  }
}



回答3:


Here is tested way to set page title on Angular 8 but you can use it on Angular 5 as well. Once you set this you have to just set title on route file and all will set automatically.

import { Component } from '@angular/core';
import { ActivatedRoute, Router, NavigationEnd } from '@angular/router';
import { Title } from '@angular/platform-browser';
import { filter, map } from "rxjs/operators";

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html'
})
export class AppComponent {

    constructor (private router: Router, private activatedRoute:    ActivatedRoute, private titleService: Title) {
        this.router.events.pipe(
            filter(event => event instanceof NavigationEnd),
            map(() => {
                let child = this.activatedRoute.firstChild;
                while (child) {
                    if (child.firstChild) {
                        child = child.firstChild;
                    } else if (child.snapshot.data &&    child.snapshot.data['title']) {
                        return child.snapshot.data['title'];
                    } else {
                        return null;
                    }
                }
                return null;
            })
        ).subscribe( (data: any) => {
            if (data) {
                this.titleService.setTitle(data + ' - Website Name');
            }
        });
    }

}

And on route file you can do something like this:

const routes: Routes = [
    {
        path: 'dashboard',
        component: DefaultDashboardComponent,
        data: {
            title: 'Dashboard'
        }
    }
];



回答4:


I would prefer to add a wrapper class just to make sure that i will not change everywhere if import {Title} from "@angular/platform-browser"; changed in the upcoming release :) ... Maybe Something called "AppTitleService"

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

@Injectable({ providedIn: 'root' })
export class AppTitleService {

    constructor(private titleService: Title) { }

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



回答5:


I just use this

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

constructor(private title: Title){}

ngOnInit() {
 this.title.setTitle('title here');
}



回答6:


For make dynamic changing title we can used angular module @angular/platform-browser and set title used function setTitle function.

For more details please check : platform-browser




回答7:


// Component.ts

import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';
import { filter } from 'rxjs/operators';

@Component({
  selector: 'app-component',
  templateUrl: './component.html',
  styleUrls: ['./component.css']
})
export class Component implements OnInit {

  constructor(private router: Router, private route: ActivatedRoute) { }

  path: string[] = [];
  pathTitle: string;

  ngOnInit() {
    this.router.events.pipe(
      filter(event => event instanceof NavigationEnd)
    ).subscribe((event: NavigationEnd) => {
        this.path = event.url.substring(1).split('/');  //  URL => stackOverflow
        this.pathTitle = this.route.root.firstChild.snapshot.data.title; // data.title => stack Overflow
    });
  }

// app-routing.module.ts
const routes: Routes = [
  { 
    path: 'stackOverflow', 
    component: Component, 
    data: {title: 'stack Overflow'}
   }
];


来源:https://stackoverflow.com/questions/47900447/how-to-change-page-title-with-routing-in-angular-application

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!