Home  >  Angular

Angular Meta Service for Meta Tags

By Arvind Rai, June 03, 2018
This page will walk through Angular Meta service for HTML meta tags. Angular provides Meta service to add, update, read and remove HTML meta tags. Meta tags are used in HTML to provide structured metadata for a web page. Meta tags has attributes such as name, httpequiv, property, content and charset. Meta tags are helpful in Search Engine Optimization (SEO) for a web page. Angular Meta service provides methods such as addTag(), getTag(), updateTag(), removeTag() etc. to add, get, update and remove HTML meta tags respectively. On this page we will provide add, update, read and remove HTML meta tag examples for description, Content-Type, robots, keywords, date, author, charset, og:title, og:type using Angular Meta service.

Technologies Used

Find the technologies being used in our example.
1. Angular 6.0.3
2. Angular CLI 6.0.3
3. TypeScript 2.7.2
4. Node.js 10.3.0
5. NPM 6.1.0

Meta

Meta class is a service in Angular to get, add, update and remove HTML meta tags. Meta has following methods.
addTag(): Adds one meta tag.
addTags(): Adds more than one meta tag.
getTag(): Returns HTMLMetaElement for the given meta attribute selector.
getTags(): Returns array of HTMLMetaElement for the given meta attribute selector.
updateTag(): Updates meta tag.
removeTag(): Removes meta tag for the given attribute selector.
removeTagElement(): Removes meta tag for the given HTMLMetaElement.

To use Meta class, import it from @angular/platform-browser library.
import { Meta } from '@angular/platform-browser'; 
Meta is an Angular service. We can instantiate it by dependency injection using constructor.
import { Injectable } from '@angular/core';
import { Meta } from '@angular/platform-browser';

@Injectable({
   providedIn: 'root'
})
export class SEOService { 
   constructor(private meta: Meta) {
   }
   ------
} 
Angular provides a type MetaDefinition that contains attributes to create HTML meta tag. Attributes of MetaDefinition are charset, content, httpEquiv, id, itemprop, name, property, scheme, url. The Meta service methods addTag, addTags and updateTag requires arguments of MetaDefinition type.

addTag()

addTag() method of Meta service adds one HTML meta tag at a time. It accepts following arguments.
tag: Instance of MetaDefinition.
forceCreation: Boolean value. Default is false.
Find the code to create meta tags for description and viewport attributes using addTag method.
@Injectable({
   providedIn: 'root'
})
export class SEOService { 
   constructor(private meta: Meta) {
       meta.addTag({name: 'description', content: 'Title and Meta tags examples'});
       meta.addTag({name: 'viewport', content: 'width=device-width, initial-scale=1'});
   }
} 
As we know that force creation is false by default. Force creation of meta tag can be enabled by passing true as following.
meta.addTag({name: 'description', content: 'Title and Meta tags examples'}, true); 
Now find more examples to add HTML meta tags using addTag method.
Add robots
meta.addTag({name: 'robots', content: 'INDEX, FOLLOW'}); 
Add author
meta.addTag({name: 'author', content: 'ABCD'}); 
Add keywords
meta.addTag({name: 'keywords', content: 'TypeScript, Angular'}); 
Add date
meta.addTag({name: 'date', content: '2018-06-02', scheme: 'YYYY-MM-DD'}); 
Add Content-Type
meta.addTag({httpEquiv: 'Content-Type', content: 'text/html'}); 
Add charset
meta.addTag({charset: 'UTF-8'}); 
Add og:title, og:type etc.
meta.addTag({property: 'og:title', content: "My Text"}); 
meta.addTag({property: 'og:type', content: "website"}); 

addTags()

addTags() method of Meta service can add more than one HTML meta tags at a time. It accepts following arguments.
tags: Instance of MetaDefinition[].
forceCreation: Boolean value. Default is false.

Find the code to add HTML meta tags using addTags() method. Here we are adding description, viewport, robots, author, keywords, date, Content-Type, og:title, og:type and charset in one go.
@Injectable({
   providedIn: 'root'
})
export class SEOService { 
   constructor(private meta: Meta) {
       meta.addTags([
          {name: 'description', content: 'Title and Meta tags examples'},   
          {name: 'viewport', content: 'width=device-width, initial-scale=1'},   
          {name: 'robots', content: 'INDEX, FOLLOW'},
          {name: 'author', content: 'ABCD'},
          {name: 'keywords', content: 'TypeScript, Angular'},
          {name: 'date', content: '2018-06-02', scheme: 'YYYY-MM-DD'},
          {httpEquiv: 'Content-Type', content: 'text/html'},
          {property: 'og:title', content: "My Text"},
          {property: 'og:type', content: "website"},
          {charset: 'UTF-8'}
       ]);       
   }
} 
Force creation of HTML meta tag can be enabled by passing true as following.
meta.addTags([
   {name: 'description', content: 'Title and Meta tags examples'},   
   {httpEquiv: 'Content-Type', content: 'text/html'},
   {charset: 'UTF-8'}
], true); 

getTag()

getTag() method of Meta service returns HTMLMetaElement instance of a HTML meta tag. getTag() accepts attribute selector. Find the example to get keywords meta tag.
@Injectable({
   providedIn: 'root'
})
export class SEOService { 
   constructor(private meta: Meta) { }
   getMetaTags() {
       let metaEl: HTMLMetaElement = this.meta.getTag('name= "keywords"');
       console.log(metaEl);
       console.log(metaEl.name);
       console.log(metaEl.content);
   }         
} 
Output will be as following.
<meta name="keywords" content="TypeScript, Angular">
keywords
TypeScript, Angular 
In the same way we can get other meta tags.
Get description
let metaEl: HTMLMetaElement = this.meta.getTag('name = "description"'); 
Get viewport
let metaEl: HTMLMetaElement = this.meta.getTag('name = "viewport"'); 
Get robots
let metaEl: HTMLMetaElement = this.meta.getTag('name = "robots"'); 
Get author
let metaEl: HTMLMetaElement = this.meta.getTag('name = "author"'); 
Get date
let metaEl: HTMLMetaElement = this.meta.getTag('name = "date"'); 
Get Content-Type
let metaEl: HTMLMetaElement = this.meta.getTag('httpEquiv = "Content-Type"'); 
Get charset
let metaEl: HTMLMetaElement = this.meta.getTag('charset'); 
Get og:title
let metaEl: HTMLMetaElement = this.meta.getTag('property = "og:title"'); 
Get og:type
let metaEl: HTMLMetaElement = this.meta.getTag('property = "og:type"'); 
If there is no HTML meta tag for the given attribute selector then we get null value.

getTags()

getTags() method of Meta service returns HTMLMetaElement[] of HTML meta tags. We need to pass attribute selector as an argument to getTags() method. Find the example to select all meta tags with name attributes.
@Injectable({
   providedIn: 'root'
})
export class SEOService { 
   constructor(private meta: Meta) { }
   getMetaTags() {
       let els: HTMLMetaElement[] = this.meta.getTags('name');
       els.forEach(el => {
          console.log(el);
          console.log(el.name);
          console.log(el.content);
       });
   }         
} 
In the same way we can fetch other meta tags. Suppose we want to fetch all author tags. We can write code as following.
let els: HTMLMetaElement[] = this.meta.getTags('name= "author"'); 
Find all meta tags with httpEquiv attribute.
let els: HTMLMetaElement[] = this.meta.getTags('httpEquiv'); 
Find all meta tags with property attribute.
let els: HTMLMetaElement[] = this.meta.getTags('property'); 

updateTag()

updateTag() method of Meta service updates a HTML meta tag. It accepts following arguments.
tag: Instance of MetaDefinition.
selector: It is optional and default value is 'undefined'.

Find the code to update description and Content-Type meta tag.
@Injectable({
   providedIn: 'root'
})
export class SEOService { 
   constructor(private meta: Meta) {
   }
   updateMetaTags() {
        this.meta.updateTag({name: 'description', content: 'Updated: Title and Meta tags examples'});
        this.meta.updateTag({httpEquiv: 'Content-Type', content: 'application/json'}, 'httpEquiv= "Content-Type"'); 
   }
} 
In the above code Content-Type is being updated with selector. It will update existing Content-Type meta tag and does not create new one. Now look into the below line of code.
this.meta.updateTag({httpEquiv: 'Content-Type', content: 'application/json'}); 
The above code will create new Content-Type meta tag. In this way there will be two Content-Type meta tags in HTML runtime source code. To avoid this, we should use selector to update meta tag.

Now find some more examples to update meta tag.
Update robots
this.meta.updateTag({name: 'robots', content: 'NOINDEX, NOFOLLOW'}); 
Update keywords
this.meta.updateTag({name: 'keywords', content: 'JavaScript, Angular'}); 
Update date
this.meta.updateTag({name: 'date', content: '2018-06-03', scheme: 'YYYY-MM-DD'}); 
Update author
this.meta.updateTag({name: 'author', content: 'VXYZ'}); 
Update charset
this.meta.updateTag({charset: 'UTF-16'}, 'charset= "UTF-8"'); 
Update og:title, og:type etc.
this.meta.updateTag({property: 'og:title', content: "My Text2"});
this.meta.updateTag({property: 'og:type', content: "website"}); 

removeTag()

removeTag() method of Meta service removes HTML meta tag for the given specified selector. Find the code to remove description and keywords HTML meta tag using removeTag().
@Injectable({
   providedIn: 'root'
})
export class SEOService { 
   constructor(private meta: Meta) { }
   removeMetaTags() {
        this.meta.removeTag('name = "description"');
        this.meta.removeTag('name= "keywords"');
   }               
} 
Find more examples to remove meta tags.
Remove viewport
this.meta.removeTag('name = "viewport"'); 
Remove robots
this.meta.removeTag('name = "robots"'); 
Remove author
this.meta.removeTag('name = "author"'); 
Remove date
this.meta.removeTag('name = "date"'); 
Remove Content-Type
this.meta.removeTag('httpEquiv = "Content-Type"'); 
Remove charset
this.meta.removeTag('charset'); 
Remove og:title
this.meta.removeTag('property = "og:title"'); 
Remove og:type
this.meta.removeTag('property = "og:type"'); 

removeTagElement()

removeTagElement() of Meta service removes HTML meta tag element for the given HTMLMetaElement instance. Find the code to remove description and keywords meta tags using removeTagElement().
@Injectable({
   providedIn: 'root'
})
export class SEOService { 
   constructor(private meta: Meta) {
   }
   removeMetaTags() {
       let description: HTMLMetaElement = this.meta.getTag('name = "description"');
       this.meta.removeTagElement(description);

       let keywords: HTMLMetaElement = this.meta.getTag('name= "keywords"');
       this.meta.removeTagElement(keywords);
   }
} 
Find more example to remove HTML meta tags using removeTagElement()
Remove viewport
let viewport: HTMLMetaElement = this.meta.getTag('name = "viewport"');
this.meta.removeTagElement(viewport); 
Remove robots
let robots: HTMLMetaElement = this.meta.getTag('name = "robots"');
this.meta.removeTagElement(robots); 
Remove author
let author: HTMLMetaElement = this.meta.getTag('name = "author"');
this.meta.removeTagElement(author); 
Remove date
let date: HTMLMetaElement = this.meta.getTag('name = "date"');
this.meta.removeTagElement(date); 
Remove Content-Type
let contentType: HTMLMetaElement = this.meta.getTag('httpEquiv = "Content-Type"');
this.meta.removeTagElement(contentType); 
Remove charset
let charset: HTMLMetaElement = this.meta.getTag('charset');
this.meta.removeTagElement(charset); 
Remove og:title
let ogTitle: HTMLMetaElement = this.meta.getTag('property = "og:title"');
this.meta.removeTagElement(ogTitle); 
Remove og:type
let ogType: HTMLMetaElement = this.meta.getTag('property = "og:type"');          
this.meta.removeTagElement(ogType); 

Complete Example

seo.service.ts
import { Injectable } from '@angular/core';
import { Meta } from '@angular/platform-browser';

@Injectable({
   providedIn: 'root'
})
export class SEOService { 
   constructor(private meta: Meta) {
        meta.addTag({name: 'description', content: 'Title and Meta tags examples'});
        meta.addTag({name: 'viewport', content: 'width=device-width, initial-scale=1'}); 
   }
   addMetaTags() {
        this.meta.addTags([
           {name: 'robots', content: 'INDEX, FOLLOW'},
           {name: 'author', content: 'ABCD'},
           {name: 'keywords', content: 'TypeScript, Angular'},
           {name: 'date', content: '2018-06-02', scheme: 'YYYY-MM-DD'},
           {httpEquiv: 'Content-Type', content: 'text/html'},
           {property: 'og:title', content: "My Text"},
           {property: 'og:type', content: "website"},
           {charset: 'UTF-8'}
        ]);
   } 
   getMetaTags() {
        let metaEl: HTMLMetaElement = this.meta.getTag('name= "keywords"');
        console.log(metaEl);
        console.log(metaEl.name);
        console.log(metaEl.content);

        let els: HTMLMetaElement[] = this.meta.getTags('name');
        els.forEach(el => {
          console.log(el);
          console.log(el.name);
          console.log(el.content);
        });
   }         
   updateMetaTags() {
        this.meta.updateTag({name: 'description', content: 'Updated: Title and Meta tags examples'});
        this.meta.updateTag({httpEquiv: 'Content-Type', content: 'application/json'}, 'httpEquiv= "Content-Type"');
        this.meta.updateTag({name: 'robots', content: 'NOINDEX, NOFOLLOW'});
        this.meta.updateTag({name: 'keywords', content: 'JavaScript, Angular'});
        this.meta.updateTag({name: 'date', content: '2018-06-03', scheme: 'YYYY-MM-DD'});
        this.meta.updateTag({name: 'author', content: 'VXYZ'});
        this.meta.updateTag({charset: 'UTF-16'}, 'charset= "UTF-8"');
        this.meta.updateTag({property: 'og:title', content: "My Text2"});
        this.meta.updateTag({property: 'og:type', content: "website"});    
    }      
    removeMetaTags() {
        //Using removeTag
        this.meta.removeTag('name = "description"');        
        this.meta.removeTag('name= "keywords"');
        this.meta.removeTag('name = "viewport"');
        this.meta.removeTag('name = "robots"');
        
        //Using removeTagElement
        let author: HTMLMetaElement = this.meta.getTag('name = "author"');
        this.meta.removeTagElement(author);
        let date: HTMLMetaElement = this.meta.getTag('name = "date"');
        this.meta.removeTagElement(date);
        let contentType: HTMLMetaElement = this.meta.getTag('httpEquiv = "Content-Type"');
        this.meta.removeTagElement(contentType);
        let charset: HTMLMetaElement = this.meta.getTag('charset');
        this.meta.removeTagElement(charset);
        let ogTitle: HTMLMetaElement = this.meta.getTag('property = "og:title"');
        this.meta.removeTagElement(ogTitle);
        let ogType: HTMLMetaElement = this.meta.getTag('property = "og:type"');          
        this.meta.removeTagElement(ogType);
    }       
} 
data.component.ts
import { Component, OnInit } from '@angular/core';
import { SEOService } from './seo.service';

@Component({
  selector: 'app-data',
  templateUrl: './data.component.html'
})
export class DataComponent implements OnInit {
  constructor(private seoService: SEOService) { }
  ngOnInit() {
    this.addMetaTags();  
  }
  addMetaTags() {
     this.seoService.addMetaTags();
  } 
  updateMetaTags() {
     this.seoService.updateMetaTags(); 
  }      
  removeMetaTags() {
     this.seoService.removeMetaTags(); 
  }       
  getMetaTags() {
     this.seoService.getMetaTags();
  }
} 
data.component.html
<button (click)="updateMetaTags()"> Update Meta Tags </button> 
<br/><br/><button (click)="getMetaTags()"> Get Meta Tags </button> 
<br/><br/><button (click)="removeMetaTags()"> Remove Meta Tags </button> 
app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
       <app-data></app-data>
  `
})
export class AppComponent {
} 
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { DataComponent } from './data.component';

@NgModule({
  declarations: [
    AppComponent,
    DataComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [ ],
  bootstrap: [ AppComponent ]
})
export class AppModule { } 

Run Application

To run the application, find the steps.
1. Download source code using download link given below on this page.
2. Use downloaded src in your Angular CLI application. To install Angular CLI, find the link.
3. Run ng serve using command prompt.
4. Access the URL http://localhost:4200
Find the print screen of the output (F12).
Angular Meta Service for Meta Tags

References

Angular doc: Meta
Angular doc: MetaDefinition

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2018 concretepage.com | Privacy Policy | Contact Us