In this article, we will explore how can we set Meta Tag dynamically in Angular
What is Meta Tag?
Meta tags are a small amount of HTML code that describes the purpose of the web page.
They are consist of metadata about the web page and mostly used to provide information about webpage content, author, keywords, viewport setting, etc.
They also provide search engines with information about a web page.
Meta Tags are usually written inside the head section of our HTML document and are not visible on our web page.
Angular comes with bundles of meta-services that we could use with meta tags.
Let us learn how can we integrate meta tags in angular. Define meta tags in angular routes, then use the meta service and navigation router event to listen to a route change, On Route change, we will update the meta tag content.
Meta Service in Angular
We use Meta services in Angular to add remove or update meta tags in angular.
Meta service Provide us with the following methods()
- addTag()
- addTags()
- getTag()
- getTags()
- updateTag()
- removeTag()
- removeTagElement
How To Use Meta Service
To use meta service we have to import it in root module and inject it in provider as shown below:-
import { NgModule } from '@angular/core'; import { BrowserModule, Meta } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule ], providers: [Meta], bootstrap: [AppComponent] }) export class AppModule { }
Dynamic Meta Tags
Adding a Meta tag in each component class is inconvenient. The preferable way is to define all the meta tags at one place where we define the routes for the angular app. On route change, we will read the tags from the route and update meta tags.
Create a new App and add two components FirstComponent and Create new App and add two components FirstComponent and SecondComponent.
Adding Meta Tags In Routes
Add the below code in app-routing. and add tags property in routes. Route data is to pass the static data or dynamic data to the routed Component as shown below.
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { FirstComponent } from './first/first.component'; import { SecondComponent } from './second/second.component'; const routes: Routes = [{ path: 'first', component: FirstComponent, data: { title: 'Title for First Component', descrption: 'Description of First Component' } }, { path: 'second', component: SecondComponent, data: { title: 'Title for Secound Component', descrption: 'Description of Second Component' } },]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
Listen to Route Changes
Whenever the user changes a route angular fires navigation events. we have to listen to each navigationEnd event.
To listen to each navigationEnd event add the below in app.component.ts
import { Component, OnInit } from '@angular/core'; import { Title, Meta } from '@angular/platform-browser'; import { Router, NavigationEnd, ActivatedRoute } from '@angular/router'; import { filter, map } from 'rxjs/operators'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { constructor(private router: Router, private activatedRoute: ActivatedRoute, private titleService: Title, private metaService: Meta ) { } ngOnInit() { this.router.events.pipe( filter((event: any) => event instanceof NavigationEnd), ) .subscribe(() => { var route = this.getChild(this.activatedRoute) var data = route.snapshot.data; this.titleService.setTitle(data.title); if (data.descrption) { this.metaService.updateTag({ name: 'description', content: data.descrption }) } else { this.metaService.removeTag("name='description'") } }) } getChild(activatedRoute: ActivatedRoute): any { if (activatedRoute.firstChild) return this.getChild(activatedRoute.firstChild); else return activatedRoute; } }
- The following code will subscribe the router change event and filter from RxJS operator filter the navigationEnd event
this.router.events.pipe( filter((event: any) => event instanceof NavigationEnd), ) .subscribe(() => {
- In the next line, we recursively call getchild() method to get the current route
this.titleService.setTitle(data.title);
after getting the Activated route of the currently loaded component we will fetch the data from the route Data
- Then we have set the title with the help of titleservice
this.titleService.setTitle(data.title);
- In the next line if the description is present in route data then we will update the meta description else we will remove the meta tag description.
app.component.html
<h1>Dynamic Meta Tag Example In Angular</h1> <span><a [routerLink]="['/first']">First Component</a></span> <span><a [routerLink]="['/second']">Second Component</a></span> <router-outlet></router-outlet>
app.module.ts
import { NgModule } from '@angular/core'; import { BrowserModule, Meta } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { FirstComponent } from './first/first.component'; import { SecondComponent } from './second/second.component'; @NgModule({ declarations: [ AppComponent, FirstComponent, SecondComponent ], imports: [ BrowserModule, AppRoutingModule ], providers: [Meta], bootstrap: [AppComponent] }) export class AppModule { }
Output:-
Hope this article helps you guys