How to add & update Canonical URL in Angular

How to add & update Canonical URL in Angular

Today I have faced a problem on changing the Canonical URL dynamically in the angular project, whenever I change the route multiple Canonical URL append in the head. So to fix the issue I have searched and viewed lots of posts but didn't find the proper solution, all post are guiding how to set up the Canonical URL but none of these for updating the Canonical URL. So I thought let's write an article that will help others who is facing the same kind of problem. So Lets start

First, add the canonical link in index.html just below the favicon.ico link. Your code will look like below after adding the canonical link.

<!-- Other Stuffs-->
 <link rel="icon" type="image/x-icon" href="favicon.ico">
 <link rel="canonical" href="http://codinghub.net/">
<!-- Other Stuffs-->

Next create ‘seo.service.ts’ service. I have created all my service under service folder for this run below command in terminals

ng g s /service/seo

and update the ‘seo.service.ts’ file code with the below code.

import { Injectable, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';

 providedIn: 'root'
export class SeoService { 

 constructor(@Inject(DOCUMENT) private doc) {}

 createLinkForCanonicalURL() { 
 let links = this.doc.getElementsByTagName("link");

The above code does the following thing.

  • We have imported the DOCUMENT So we can manipulate the dom element and in angular DOCUMENT represent the browser dom element.
  • The function createCanonicalURL uses Angular document to update a link href and set canonical URL and appends it to the HEAD section. It will get all links available in DOM & update the 2nd link href value which is our Canonical URL.

Next & final step is to call this method from the active route component inside ngOnInt. so canonical url will update with new URL. Import ‘seo.service.ts’ in your component & inject in constructor

import { ShareService } from '../services/share.service';

constructor(private seoService: SeoService) {}

ngOnInit() { 
    // add canonical link

Now just run your angular project and visit any page to see the code in action. Canonical URL will change according to active page URL.

That's it. Thanks for the reading I hope this will help you!

You may like: Update Meta tags dynamically for Facebook (Open graph)

Related Articles