ルーターからページのタイトルを変更しようとしていますが、変更できますか?
import {RouteConfig} from 'angular2/router';
@RouteConfig([
{path: '/home', component: HomeCmp, name: 'HomeCmp' }
])
class MyApp {}
ルーターからページのタイトルを変更しようとしていますが、変更できますか?
import {RouteConfig} from 'angular2/router';
@RouteConfig([
{path: '/home', component: HomeCmp, name: 'HomeCmp' }
])
class MyApp {}
これを行うのは非常に簡単です。これらの手順に従って、すぐに効果を確認できます。
ブートストラップでタイトル サービスを提供します。
import { NgModule } from '@angular/core';
import { BrowserModule, Title } from '@angular/platform-browser';
import { AppComponent } from './app.component';
@NgModule({
imports: [
BrowserModule
],
declarations: [
AppComponent
],
providers: [
Title
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
次に、必要なコンポーネントにこのサービスをインポートします。
import { Component } from '@angular/core';
import { Title } from '@angular/platform-browser';
@Component({
selector: 'my-app',
template:
`<p>
Select a title to set on the current HTML document:
</p>
<ul>
<li><a (click)="setTitle( 'Good morning!' )">Good morning</a>.</li>
<li><a (click)="setTitle( 'Good afternoon!' )">Good afternoon</a>.</li>
<li><a (click)="setTitle( 'Good evening!' )">Good evening</a>.</li>
</ul>
`
})
export class AppComponent {
public constructor(private titleService: Title ) { }
public setTitle( newTitle: string) {
this.titleService.setTitle( newTitle );
}
}
これらのリンクをクリックして、タイトルの変更を確認してください。
ページのタイトルと説明を変更するために ng2-meta を使用することもできます。次のリンクを参照できます。
ページ/ビューがナビゲートされたときにページのタイトルを変更する最も簡単な方法は次のとおりです (Angular @2.3.1 でテスト済み)。持っているすべてのビューに次のソリューションを適用するだけで、準備完了です。
About Usページ/ビューのコード例:
import {Title} from "@angular/platform-browser";
export class AboutUsComponent implements OnInit {
constructor(private _titleService: Title) {
}
ngOnInit() {
//Set page Title when this view is initialized
this._titleService.setTitle('About Us');
}
}
お問い合わせページ/ビューのコード例:
import {Title} from "@angular/platform-browser";
export class ContactusComponent implements OnInit {
constructor(private _titleService: Title) {
}
ngOnInit() {
//Set page Title
this._titleService.setTitle('Contact Us');
}
}
ページ タイトルとメタ タグを動的に設定する方法を探している場合は、リリースしたばかりの @ngx-meta/coreプラグイン プラグインもお勧めします。
タイトルを設定する簡単な一般的な方法:
import { Component } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { ActivatedRoute, Router, NavigationEnd } from '@angular/router';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
constructor(
private activatedRoute: ActivatedRoute,
private router: Router,
private titleService: Title
) {}
ngOnInit() {
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
const { title } = this.activatedRoute.firstChild.snapshot.data;
this.titleService.setTitle(title);
}
});
}
}
title
次のように各ルートで設定する必要があります。
{ path: '', component: WelcomeComponent, data: {title: 'Welcome to my app'} }