Dynamic Title, Meta, SEO Tags binding — Angular
Update page title/SEO Meta tags based on Route

Setting Page Title or Meta tags:
Angular provides ways to set title or add/update Meta tags through Title, Meta services. You can import Title, Meta from @angular/platform-browser
. This information can be changed in constructor/ngOnInit() or in any function inside the component. This helps in dynamically binding the values for the page, instead of the title being set in index.html
or app.component.ts file
.
import { Title, Meta } from "@angular/platform-browser";...constructor(private titleService:Title, private metaService: Meta) {
this.titleService.setTitle("My page title");
this.metaService.addTag({ name: 'description', content: 'changing tags' });this.metaService.updateTag({ name: 'description', content: 'changing tags' });}
Dynamic binding based on routes:
Often the page titles may change based on views. Some cases we may need to have new meta tags based on current view(route). Angular provides a way to keep a simple name value collection, attached to specific routes. We can keep the list of items needed as tags and title in the Route definition.
const routes: Routes = [
{
path: 'landingpage',
component: LandingPageComponent,
data: {
title: 'My Title',
meta:'My landing page'
}
}
]
We can retrieve the information from routes, and update the title based on the data in the Route definition.
import { Title, Meta } from "@angular/platform-browser";...constructor(private titleService:Title, private metaService: Meta) {
this.route.data.subscribe(value => {
// contains meta tag and title. update
this.meta = value.meta;
this.title = value.title;
}); this.titleService.setTitle(this.title);
this.metaService.addTag({ name: 'description', content:
this.meta });
this.metaService.updateTag({ name: 'description', content:
this.meta });
}
In Conclusion:
Data: Represents static data associated with a particular route. Data associated with a route can be used to update Title and meta tags dynamically based on views.