国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

Angular 2 利用Router事件和Title實(shí)現(xiàn)動(dòng)態(tài)頁面標(biāo)題的方法

2024-05-06 15:12:23
字體:
供稿:網(wǎng)友

Angular2 為我們提供了名為Title的Service用于修改和獲取頁面標(biāo)題,但是如果只是能夠在每個(gè)頁面的ngOnInit方法中為每個(gè)頁面設(shè)置標(biāo)題豈不是太low了,不符合Angular2高(zhuang)大(bi)的身影。我們想要的結(jié)果是在頁面改變時(shí)能夠動(dòng)態(tài)地改變頁面標(biāo)題,如此最好的解決方案就是組合使用Router事件和Title Service。

Title Service

使用Service自然首先要將其引入,不過要注意Title Service并不在@angular/core中,而是在@angular/platform-browser中:

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

引入之后,自然要將其注入到當(dāng)前組件中,而這通常利用constructor完成:

import { Title } from '@angular/platform-browser';import {Component} from '@angular/core';@Component({})export class AppComponent {  constructor(private titleService: Title) {    // 使用this.title到處浪  }}

很顯然,Title Service應(yīng)該有某些操作頁面標(biāo)題的方法,不管通過查找文檔還是查找源碼我們都能很容易知道其只有兩個(gè)方法:

getTitle() 用于獲取當(dāng)前當(dāng)前頁面的標(biāo)題 setTitle(newTitle: String) 用于設(shè)置當(dāng)前頁面的標(biāo)題

如果只是簡單地靜態(tài)地設(shè)置頁面標(biāo)題,則可以在ngOnInit方法中直接使用setTitle方法:

// import bala...@Component({})export class AppComponent implements OnInit {  constructor(private titleService: Title) {    // 使用this.title到處浪  }  ngOnInit() {    this.titleService.setTitle('New Title Here');  }}

在ngOnInit中使用setTitle方法設(shè)置文檔標(biāo)題是較好的時(shí)機(jī),當(dāng)然也可以根據(jù)自己的需求在任意地方使用setTitle方法。

Router和Router事件

使用Router和使用Title Service流程基本一致,先引入后注入,不過要注意Router和Title Service類似并不位于@angular/core中,而是位于@angular/router中:

import { Title } from '@angular/platform-browser';import {Component} from '@angular/core';import {Router} from '@angular/router';@Component({})export class AppComponent {  constructor(private titleService: Title, private router: Router) {    // 使用this.title和this.router到處浪  }}

Router配置

Angular2中通過URL、Router和Component之間的對應(yīng)關(guān)系進(jìn)行頁面之間的跳轉(zhuǎn),Router把瀏覽器中的URL看做一個(gè)操作指南,據(jù)此可導(dǎo)航到一個(gè)由客戶端生成的視圖,并可以把參數(shù)傳給支撐視圖的相應(yīng)組件。所以我們需要定義路由表:

// import bala...export const rootRouterConfig: Routes = [ { path: '', redirectTo: 'home', pathMatch: 'full'}, { path: 'home', component: HomeComponent, data: {title: 'Home-Liu'} }, { path: 'about', component: AboutComponent, data: {title: 'About-Liu'} }, { path: 'github', component: RepoBrowserComponent,  children: [   { path: '', component: RepoListComponent, data: {title: 'GitHub List'} },   { path: ':org', component: RepoListComponent,    children: [     { path: '', component: RepoDetailComponent, data: {title: 'Repo'} },     { path: ':repo', component: RepoDetailComponent, data: {title: 'RepoDetail'} }    ]   }] }, { path: 'contact', component: ContactComponent, data: {title: 'Contact-Liu'} }];             
發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 罗江县| 赣州市| 贵港市| 石阡县| 延庆县| 尼勒克县| 浙江省| 叙永县| 青海省| 泌阳县| 开阳县| 皋兰县| 宣化县| 彭水| 丁青县| 措美县| 清流县| 屏东市| 柳江县| 尼木县| 寿光市| 万荣县| 噶尔县| 阿勒泰市| 奉节县| 霸州市| 醴陵市| 聂荣县| 沙雅县| 昌图县| 沙坪坝区| 苗栗市| 横峰县| 昭平县| 龙里县| 九寨沟县| 会理县| 龙游县| 北辰区| 南宁市| 胶南市|