How To Add/Update Meta Tags In Angular

How To Add/Update Meta Tags In Angular

In this article, we will learn how to use Angular's Meta Service to add/update HTML Meta tags. Setting various meta tags for various pages is simplified by the Angular Meta Service. It offers methods like updateTag(), removeTag(), removeTagElement(), addTag(), addTags(), getTag(), getTags(), and many others. They can be used to change meta tags. Let's use an example to learn how to use the Meta service.

Why Set Meta Tags

For search engines, meta tags provide information about the content of your page. Therefore, choosing the appropriate Meta tags is crucial for SEO. These tags don't show up in the user's view because they only occur in the HTML's <head> section. However, they're used by social networking platforms and search engines to learn more about your page. A typical <head> section's meta tags might resemble this.

<head>
  <title>Setting HTML Meta Tags Angular Meta service Example</title>
  <meta content="width=device-width, initial-scale=1" name="viewport"></meta>
  <meta content="”Angular" example="" meta="" name="”description”" service=""></meta>
  <meta content="”Index,follow”" name="”robots”"></meta>
  <meta content="Content Title for social media" property="og:title"></meta>
  <meta charset="UTF-8"></meta>
</head>

Meta service

The following methods are available through Angular's Meta service to modify HTML Meta tags.

How to Use Meta Service

Importing Meta Service

We must first import the meta service into the Root module before we can use it. Due to the fact that it only applies to apps running in browsers, the Meta service is a component of the @angular/platform-browser library.

import { BrowserModule, Meta } from '@angular/platform-browser';

Then, as shown below, we must add it to the Angular Providers metadata.

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

All you have to do to use the service in components is inject it using dependency injection.

then use any of the Meta Service's methods to alter the Tags. Either ngOnInit or the constructor are options.

import { Component, OnInit } from '@angular/core';
import { Meta, MetaDefinition } from '@angular/platform-browser';
 
@Component({
  template: `<h1>Home Component</h1>`
})
export class HomeComponent implements OnInit {
  title = 'Home Component Title';
 
  constructor(private metaService:Meta){
  }
 
  ngOnInit() {
    this.metaService.addTag( { name:'description',content:"Article Description"});
  }
 
}

Meta Definition Class

A meta element is represented by the meta definition class.

type MetaDefinition = {
    charset?: string;
    content?: string;
    httpEquiv?: string;
    id?: string;
    itemprop?: string;
    name?: string;
    property?: string;
    scheme?: string;
    url?: string;
} & {
    [prop: string]: string;
};

Using the Meta Service, we construct objects of the type MetaDefinition and add them. As An Example

{name: 'description', content: 'Title and Meta tags examples'}

and the resulting HTML is as follows.

<meta angular="" content="”Setting" example="" html="" meta="" name="”description”" service="" tags=""></meta>

Similarly,
{charset: 'UTF-8'}                              
=>  <meta charset="UTF-8"></meta>
 
{meta name="robots" content="Index,follow"}     
====>  <meta content="”Index,follow”" name="”robots”"></meta>
 
{meta name="viewport" content="width=device-width, initial-scale=1"}     
====>  <meta content="width=device-width, initial-scale=1" name="viewport"></meta>

Adding Tags with addTag() & addTags()

We use the methods addTag() or addTags to add a new tag or tags ().

We are able to add a single tag using addTag().

Syntax

addTag(tag: MetaDefinition, forceCreation: boolean = false): HTMLMetaElement | null

Example

constructor(private metaService: Meta) {
    this.addTag();
}
 
addTag() {
   this.metaService.addTag({ name: 'description', content: 'Article Description' });
   this.metaService.addTag({ name: 'robots', content: 'index,follow' });
   this.metaService.addTag({ property: 'og:title', content: 'Content Title for social media' });
}

The HTML that results is as follows.

<meta content="Article Description" name="description"></meta>
<meta content="index,follow" name="robots"></meta>
<meta content="Content Title for social media" property="og:title"></meta>

whereas addTags() enables us to add multiple tags

Syntax

addTags(tags: MetaDefinition[], forceCreation: boolean = false): HTMLMetaElement[]

constructor(private metaService: Meta) {
    this.addTags();
}
  
addTags() {
   this.metaService.addTags([
     { name: 'description', content: 'Article Description' },
     { name: 'robots', content: 'index,follow' },
     { property: 'og:title', content: 'Content Title for social media' }
  ]);
}

Duplication of Meta tags

If the meta tag is already there, the angular does check for it. It won't let you add the meta tag if it already exists. Making the forceCreation=true setting will make it add the tag.

Angular does check for duplicate meta tags, but you shouldn't rely on it.

Only when all of the attribute values are equal are the meta tags considered equal.

The produced HTML code from the following code only produces one HTML meta tag.

constructor(private metaService: Meta) {
    this.duplicateTags();
}
 
duplicateTags() {
  this.metaService.addTag( { name: 'description', content: 'Article Description' })
  this.metaService.addTag( { name: 'description', content: 'Article Description' })
}


//output
<meta content="Article Description" name="description"></meta>

While the code below causes both meta tags to appear in the HTML that is produced.

constructor(private metaService: Meta) {
    this.duplicateTags();
}
 
duplicateTags1() {
    this.metaService.addTag( { name: 'description', content: 'Article Description' })
    this.metaService.addTag( { name: 'description', content: 'A different Article Description' })
}


//output
<meta content="Article Description" name="description"></meta>
<meta content="A different Article Description" name="description"></meta>

Only the first instance is checked

Angular only look for duplicates in the first instance of the meta tag. To find the first use of the meta tag and check for duplication, it employs either name or property.

  duplicateTags2() {
    this.metaService.addTag( { name: 'description', content: 'Article Description' })
    this.metaService.addTag( { name: 'description', content: 'A different Article Description' })
    this.metaService.addTag( { name: 'description', content: 'Description of the Article' })   //Not Inserted
    this.metaService.addTag( { name: 'description', content: 'A different Article Description' })    //Inserted
  }

output

<meta content="Article Description" name="description"></meta>   //Appears only once
<meta content="A different Article Description" name="description"></meta>  
<meta content="A different Article Description" name="description"></meta>  //Not checked for duplication

will produce the HTML below. Be aware that Angular generates a copy of a distinct description of the component rather than duplicating the component's description.

Reading the Tags

Use the getTag() and getTags() methods to read meta tags. GetTags() reads all instances of the meta tag, whereas getTag() only reads the first instance.

Syntax

getTag(attrSelector: string): HTMLMetaElement | null
getTags(attrSelector: string): HTMLMetaElement[]

Examples

getTag() {
  this.metaService.addTag({ name: 'description', content: 'Article Description' });
  this.metaService.addTag({ name: 'robots', content: 'index,follow' });
  this.metaService.addTag({ property: 'og:title', content: 'Content Title for social media' });
  this.metaService.addTag({ name: 'description', content: 'Another Article Description' });
}

The initial instance of the corresponding meta tag is returned by the getTag() method. The syntax attributeName='value' is required when passing an attribute name and value. There is only one attribute you can look for. Multiple attribute searches are not supported.

this.metaService.getTag("name='description'")

output in the console window

<meta content="Article Description" name="description"></meta>

You can use it to contrast any of the qualities. The content attribute is used to read the data in the example that follows.

console.log(this.metaService.getTag("content='Article Description'"));

output in the console window

<meta content="Article Description" name="description"></meta>

All instances of the meta are returned in an array by the getTags() method.
console.log(this.metaService.getTags("name='description'"));

output

<meta content="Article Description" name="description"></meta>
<meta content="Another Article Description" name="description"></meta>

The next will list all meta tags that have the name property.
console.log(this.metaService.getTags("name"));

output. Returns an array of the following meta tags

<meta content="Article Description" name="viewport"></meta>
<meta content="width=device-width, initial-scale=1" name="description"></meta>
<meta content="index,follow" name="robots"></meta>
<meta content="Another Article Description" name="description"></meta>

Additionally, take a look at the list below.

console.log(this.metaService.getTags("property"));
console.log(this.metaService.getTags("content"));

Update the Tag

Based on search criteria, the updateTag() method replaces the current meta tags with the new ones (first argument). Similar to the getTag method, specify the search criteria as the second argument in the format attributeName='value'.

Syntax

updateTag(tag: MetaDefinition, selector?: string): HTMLMetaElement | null

Add the Tag

this.metaService.addTag({ name: 'robots', content: 'index,follow' });

output

<meta content="index, follow" name="robots"></meta>

Now update the Tag

this.metaService.updateTag( { name:'robots', content:'index, nofoloow'},"name='robots'");

Output

<meta content="index, nofoloow" name="robots"></meta>

If a matching meta element is not found, updateTag inserts the tag.
this.metaService.updateTag( { name:'description', content:'Article Description'},"name='description'");

Will insert the Meta if it is not found

<meta content="Article Description" name="description"></meta>

Only the first occurrence of the search criterion is replaced by updateTag.
this.metaService.addTag({ property: 'og:title', content: 'Social Media descripton'});
this.metaService.addTag({ property: 'og:title', content: 'Duplicate Social Media descripton'});

output

<meta content="Social Media descripton" property="og:title"></meta>
<meta content="Duplicate Social Media descripton" property="og:title"></meta>

Now run this

this.metaService.updateTag( { property:'og:title', content:Social Media 'Description of the component'},"property='og:title'");

output

<meta content="Description of the componen" property="og:title"></meta>     //Updated
<meta content="Duplicate Social Media descripton" property="og:title"></meta>  //Not touched

Removing the Tag

To delete the meta tag, use the removeTag() or removeTagElement() elements.

Syntax

removeTag(attrSelector: string): void
removeTagElement(meta: HTMLMetaElement): void

The robots metatag is added in the following example, which uses the removeTag to then remove it. The first incidence of the corresponding meta tag is eliminated by removeTag. The syntax attributeName='value' is required when passing an attribute name and value. Only one attribute can be used for searching.

Example

Adding the Meta Tag

this.metaService.addTag({ name: 'robots', content: 'index,follow' });

Output

<meta content="index,follow" name="robots"></meta>

Remove it 

this.metaService.removeTag("name='robots'");

removes the first tag that matches.

Adds two meta tags

this.metaService.addTag({ property: 'og:title', content: 'Social Media descripton'});
this.metaService.addTag({ property: 'og:title', content: 'Duplicate Social Media descripton'});

This will remove the first one

this.metaService.removeTag("property='og:title'");

Any meta-attribute may be used. The content attribute is used to eliminate it in the example that follows.

Adds the meta tag

this.metaService.addTag({ property: 'og:title', content: 'Duplicate Social Media descripton'});

Output

<meta content="Duplicate Social Media descripton" property="og:title"></meta>

This will remove it

this.metaService.removeTag("content='Duplicate Social Media descripton'");

The meta can be eliminated using removeTagElement(). The HTMLMetaElement that you want to remove must be passed. For instance,

Ads two meta property

this.metaService.addTag({ property: 'og:title', content: 'Social Media descripton'});
this.metaService.addTag({ property: 'og:title', content: 'Duplicate Social Media descripton'});

Removes the first instance of the 'og:title'

this.metaService.removeTagElement(this.metaService.getTag('property'));

Conclusion

In this article, we learned how to use Angular's Meta Service to add/update HTML Meta tags using examples.

I hope this article helps you and you will like it.👍

If you have any doubt or confusion then free to ask in the comment section.

Post a Comment

Previous Post Next Post