天天看點

Angular8 動态設定頁面标題title

一般情況下在頁面修改标題需要在每個頁面元件裡引入:

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


constructor(
    private titleService: Title
) { }

this.titleService.setTitle("title");
           

    但是,在每個頁面都寫一次是不是很繁瑣呢,也不利于管理标題。可以将設定标題封裝成一個services服務,達到統一修改title的目的。

1. 修改頁面入口檔案index.html

<!doctype html>
<html >
<head>
  <meta charset="utf-8">
  <title>{{title}}</title>
  <base href="/" target="_blank" rel="external nofollow" >
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico" target="_blank" rel="external nofollow" >
</head>
<body>
  <app-root></app-root>
</body>
</html>
           

2. 配置頁面的路由,設定data屬性中的title

const routes: Routes = [
  { path: '',   redirectTo: '/login', pathMatch: 'full' },
  { path: 'login', component : LoginComponent , data : { title : "登入" }},
  { path: 'index', loadChildren: () => import('./pages/index/index.module').then(m => m.IndexModule), data : { title : "首頁" } },
  { path: '**', component: NotFoundComponent , data : { title : "404" }}
];
           

3.建立一個公共服務CommonService

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

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

  constructor(
    private router: Router,
    private titleService: Title
) {}

  public setTitle() {
    this.router.events.pipe(
        filter(event => event instanceof NavigationEnd),
        map(() => this.router)
      )
      .subscribe((event) => {
        const titles = this.getTitle(this.router.routerState, this.router.routerState.root);
        const title = titles[titles.length - 1];
        // console.log(title);
        if (title) {
          this.titleService.setTitle(title);
        }
      });
  }

  public 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;
  }
}
           

4.在根子產品

app.component.ts

中調用

        引用注入公共服務

CommonService,并調用

setTitle設定title

import { Component } from '@angular/core';

import { CommonService } from "@services/common.service";

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

  constructor(
    private common: CommonService
  ) { }

  ngOnInit() {
    //設定頁面标題
    this.common.setTitle();
  }
}
           

5.運作結果

Angular8 動态設定頁面标題title