5

In angular 2 how can I make the canonical tag dynamic per page.

This is my index page tag for it:

  <link rel="canonical" href="https://mywebsite.co.uk" />

How can I make it dynamic e.g. if on blog page it should look like this at run time:

  <link rel="canonical" href="https://mywebsite.co.uk/blog" />

I'm using angular version 4, webpack and typescript with ng2-metadata to change the title, description and keywords of all my urls.

I just need the canonical tag to change for the seo google bot.

David L
  • 32,885
  • 8
  • 62
  • 93
AngularM
  • 15,982
  • 28
  • 94
  • 169

1 Answers1

0

I implemented a service that is called in the ngOnInit functions of my page components:

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

@Injectable()
export class LinkService {

  private link: HTMLLinkElement;

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

  createLinkForCanonicalURL() {
    if (this.link === undefined) {
      this.link = this.doc.createElement('link');
      this.link.setAttribute('rel', 'canonical');
      this.doc.head.appendChild(this.link);
    }
    this.link.setAttribute('href', this.doc.URL.split('?')[0]);
  }
}

Source: https://www.concretepage.com/angular/angular-title-service-and-canonical-url

Alexandra
  • 500
  • 8
  • 20