Angularでtitleとdescriptionをページごとに設定してみようかなと思って調べてみたら、簡単な方法は見つかりましたのでシェアしたいと思います
とりあえず、まずはプロジェクトを作ります
$ ng new seo-sample # 終わったら $ ng serve
完了したら、localhost:4200 にアクセスします
うおーすげえ!
最近プロジェクトを作っていなかったので知らなかったんですけど、こんな画面になってます!!!

話が脱線してしまいましたが、本題に戻ります
デフォルトだと、titleは
<title>SeoSample</title>
になっていて、descriptionはありません
こんな感じになっています

このtitleとdescriptionを管理するには以下のように app.component.tsを修正します
import {Component, OnInit} from '@angular/core';
// metaタグの設定とかできるようにするため + titleを入れたり修正したり
import {Meta, Title} from '@angular/platform-browser';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
constructor(private meta: Meta,
private title: Title) {
}
ngOnInit() {
this.setDescription('せんべいうまい。特に黒豆のやつやばい。のりも捨て難い');
this.setTitle('SeoSampleについて | せんべいって美味しいよね');
}
setDescription(description: string) {
// ブログなどのデータを入れる場合はなんどもdescriptionが追加されてしまうため、
// descriptionを入れる前に既存のdescriptinoを削除しておく
this.meta.removeTag("name='description'");
this.meta.addTag({name: 'description', content: description});
}
setTitle(title: string) {
this.title.setTitle(title);
}
}
すると以下のようにtitleとdescriptionが変更されてるのがわかるかと思います

とりあえずは、これで簡単にSEO対策はできます
簡単なホームページの場合であれば、そこまで考えることは必要無いかもしれませんが、
ルーティングが複雑になる状況や、個別にdescriptinやtitleを設定することで集客力などを向上させて行く際は必ずやるべきことだと思います
ただ、難しいことはしていないのでやるべきこととしては、seo.service.tsを作ってできる限り綺麗にまとめとくことぐらいですかね
どのページにも入れなきゃいけないと思うんで
参考にした記事
Meta
Angular2 – SEO – how to manipulate the meta description
Angular 4.0 Platform Server Ability to Set Title and Meta Tags #15742

コメントを残す