Angular で初期化時にTitleサービスを使用してタイトルを設定する – ngOnInit
src – index.htmlでタイトルを設定していますが、初期化時にタイトルを変更することができます。
app.component.tsをOnInitインターフェースをインプリメントします。
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
ngOnInit() {
}
}
次に、’@angular/platform-browser’からTitleをインポートします。setTitleメソッドがあるので、引数にタイトルをそのままセットすれば初期化時にタイトルが設定されます。
import { Component, OnInit } from '@angular/core';
import { Title } from '@angular/platform-browser';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'タイトルをここで指定する';
constructor(private titleObj: Title) {
}
ngOnInit() {
this.titleObj.setTitle(this.title);
}
}
constructorで初期化するのではなく、AngularライフサイクルのngOnInit()で初期化します。
詳細は「AngularとTypeScriptでSPAを作成する」を参照ください。

KHI入社して退社。今はCONFRAGEで正社員です。関西で140-170/80~120万から受け付けております^^
得意技はJS(ES6),Java,AWSの大体のリソースです
コメントはやさしくお願いいたします^^
座右の銘は、「狭き門より入れ」「願わくは、我に七難八苦を与えたまえ」です^^



コメント