Angular — ActivationEnd動態轉換網站標題

Charlie Chen (陳慶裕)
4 min readAug 15, 2018

--

這次談的需求是每次在轉換component時,必需隨著變動網站頁籤標題,如下效果:

當然作法有很多種,有些是只在component就可以做解決,但是若遇到大型網站的話,這顯然不是很好的作法,因為必需每個component手動去做設定是相當累人,所以官方提供了ActivationEnd進行特殊實作,可參考它的註釋:

ActivationEnd

Represents the start of end of the Resolve phase of routing. See note on ActivationStart for use of this experimental API.

意思是在啟動routing成功結束時所啟動的方法,而我們也可以在其中獲得事先所定義好的字串,在進行component轉換時擷取字串設定為網站頁籤標題,實作如下:

app.module.ts

import { BrowserModule, Title } from '@angular/platform-browser';
@NgModule({
declarations: [AppComponent],...
imports: [...],
providers: [Title,...]
...

app.routes.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
const routes: Routes = [{
path: 'see-more',
component: SeeMoreComponent,
data: { title: 'See More in Smarter Ways' }
},
{
path: 'people-counting',
component: PeopleCountingComponent,
data: { title: 'People Counting' }
},
...

app.component.ts

import { Router, ActivationEnd } from '../../../../node_modules/@angular/router';
import { filter } from '../../../../node_modules/rxjs/operators';
export class AppComponent {
title = 'Hello-Official ';
constructor(
private router: Router,
private titleService: Title
) {
this.router.events
.filter((event) => event instanceof ActivationEnd)
.subscribe((event: ActivationEnd) => {
console.log(event);
let dataTitle = event.snapshot.data['title'];
if (dataTitle) {
this.titleService.setTitle(this.title + dataTitle);
return dataTitle;
}
});
}
}

這邊使用到 this.titleService.setTitle() 這是官方所提供設置標題的方法,另一個則是 this.titleService.getTitle() 顧名思意為取得目前的標題字串,只需用內建的方法就可以實作動態標題,相當方便。

另外,網路上也有其它作法,而此方法是自己觀察console.log試出來的,所以並非適用於任何情況,供各位參考方向,謝謝。

原參考:
https://github.com/doggy8088/sb-admin-2-ng6/blob/master/src/app/layout/layout.component.ts

--

--

Charlie Chen (陳慶裕)
Charlie Chen (陳慶裕)

No responses yet