
***Angular Meta service ใช้ได้ตั้งแต่ Angular 4+ เป็นต้นไป
updateTag ใช้สำหรับ update tag เดิม (ไล่มาจาก HomeComponet || component แรกที่ถูกเรียก)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import {Meta, Title} from "@angular/platform-browser"; export class ViewComponent implements OnInit { ngOnInit( ) { this._setMetaAndLinks(); } private _setMetaAndLinks(){ this.title.setTitle(this.PostTitle); this.meta.updateTag({ name: 'description', content: this.PostTitle + ' - Kaset.info' },`name='description'`); this.meta.updateTag({ property: 'og:title', content: this.PostTitle + ' - Kaset.info' },`property='og:title'`); this.meta.updateTag({ property: 'og:image', content: 'https://www.kaset.info/u/'+this.photo.FileName },`property='og:image'`); } } |
addTags ถ้าอยากเพิ่ม mata เข้าไปใหม่
1 2 3 |
this.meta.addTags([ { name: 'twitter:site', content: 'https://www.kaset.info' }, ]); |
กำหนดไปพร้อมกับ route ได้ เหมาะสำหรับหน้าที่ meta ไม่ได้เปลี่ยนตาม content
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
export const appRoutes: Routes = [ { path: '', redirectTo: 'home', pathMatch: 'full' }, { path: 'home', component: HomeComponent, data: { title: 'Homepage', meta: [ { name: 'description', content: 'ร่วมแบ่งปันเรื่องราวการทำเกษตร วิถีชีวิตการทำเกษตร แชร์เทคนิคการเกษตร และแบ่งปันผลผลิตคุณภาพดี ราคากันเอง ได้แล้วที่ Kaset.info'}, { property: 'og:title', content: 'ร่วมแบ่งปันเรื่องราวการทำเกษตร วิถีชีวิตการทำเกษตร แชร์เทคนิคการเกษตร และแบ่งปันผลผลิตคุณภาพดี ราคากันเอง ได้แล้วที่ Kaset.info'}, { property: 'og:image', content: 'https://www.kaset.info/images/logo.png' } ], links: [ {rel: 'canonical', href: 'https://www.kaset.info'}, ] } } } |
นอกจาก update กับ add แล้ว เรายังสามารถ get meta ได้ด้วย
1 |
const viewport = this.meta.getTag('name=viewport'); |
ตามมาด้วยการลบ tag
1 |
this.meta.removeTag('charset'); |
จบ..ครับ note เล็กๆ เผื่อใครได้เอาไปใช้ประโยชน์ครับ