{%hackmd BJzAwtWvp %} # [問題]如何修改Angular中,每個routes的title? [參考資料-Angular — ActivationEnd動態轉換網站標題](https://jscinin.medium.com/angular-navigationend%E5%8B%95%E6%85%8B%E8%BD%89%E6%8F%9B%E7%B6%B2%E7%AB%99%E6%A8%99%E9%A1%8C-%E5%BE%85-f05d83ea7d5d) * 就是問怎麼修改這個呢?  1. 首先在index.html中不要寫 `<title></title>` 2. app.module.ts加入 ``` import { BrowserModule, Title } from '@angular/platform-browser'; @NgModule({ declarations: [AppComponent],... imports: [...], providers: [Title,...] ... ``` 3. app.routes.ts加入某一path想要的title ``` const routes: Routes = [{ path: 'see-more', component: SeeMoreComponent, data: { title: 'See More in Smarter Ways' } }, { path: 'people-counting', component: PeopleCountingComponent, data: { title: 'People Counting' } }, ... ``` 4. app.component.ts加入 這邊使用到 this.titleService.setTitle() 這是官方所提供設置標題的方法,另一個則是 this.titleService.getTitle() 顧名思意為取得目前的標題字串,只需用內建的方法就可以實作動態標題,相當方便。 ``` constructor( private router: Router, private titleService: Title ) { this.router.events.subscribe((event) => { if (event instanceof ActivationEnd) { this.titleService.setTitle(event.snapshot.data.title); } }) } ``` --- ###### tags: `angular`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up