Angular如何修改頁面的標題(Title)

分享一個Angular的開發小技巧,說一下如何修改頁面的標題(Title)。

Angular如何修改頁面的標題(Title)

分享一個Angular的開發小技巧,說一下如何修改頁面的標題(Title)。

路由中加入參數來傳入Data

Angular2在路由设置里提供了data参数可以传值,如下︰

const routes: Routes = [
  {
    path: '',
    component: AppComponent,
    data: { title: 'NA'}
  },
  {
    path: 'home',
    component: AppComponent,
    data: { title: 'home'}
  },
  {
    path: 'index',
    component: AppComponent,
    data: { title: 'index'}
  } 
];
  • path是地址栏的显示。

  • component是调用的组件。

  • data则可以传数据,在组件内可以调用。

[memo]  angular2里默认切换路由或者切换组件,页面的title是不会变化的。

 

調用Title服务可以修改頁面title

接者,我們先import 相關的核心服務(Title)

同時,可以用ActivatedRoute的snapshot的data属性,來获取當前路由内获取设置的参数

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Title } from '@angular/platform-browser';
import { environment } from '../environments/environment';
​
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  routeconfig: any;
  title = 'angular-bh';
  appname: string;
​
  constructor(
    private activateroute: ActivatedRoute,
    private titleservice: Title
  ) { }
​
  ngOnInit(): void {
    this.appname = environment.appName;
    this.title = this.appname
    
    // Get the config information from the app routing data
    this.routeconfig = this.activateroute.snapshot.data;
​
    // Set the page title
    this.titleservice.setTitle(this.appname + "--" + this.routeconfig.title);
​
  }
  
}
​

 

Category

Angular

Keywords

Modern Web / Angular

 

License

使用 MIT 许可证发布。 详情请进入 LICENSE 查看。

 

Skyfu160