Angular, SEO

How to set angular canonical url link

Spread the love

What is canonical url?

A canonical URL is a technical solution for duplicate content. For example, you may have a post or product attached to two categories and available under two URLs, thus:

https://example.com/red-shirt/white-and-red-shirt/
https://example.com/white-shirt/white-and-red-shirt/

If these URLs are for the same product, choose one as the canonical URL that tells Google and other search engines which one should be shown in the search results.

Canonicals also enable you to target search engines in the first version of the article. Suppose you wrote a post for another group that was published on their website. If you would like to send it to your site again, you may agree to send it canonical in the original version.

Why should I choose a canonical URL?
Dynamically add meta tags based on route in Angular

How to find a canonical URL?

The canonical URL can be seen in the source of a web page, by searching rel = “canonical”. It is only visible to search engines, your users will not be affected by it.

If you Implement it then you can find it from view source of that web page

how to find a canonical url

Dynamically Updating Canonical URL

We can use the router to dynamically refresh the canonical URL. Show us how to set up a title with the power of Title Service. You can also look at the Dynamic Meta Tags in Angular, which uses the same process. We use the same process to update the canonical URL.

First, update the routes and insert a canonical tag into the Route Data for each route.

The hostName is hardcoded in the example below. You can set dynamic variable by import environment variable setup.

import { Injectable } from "@angular/core";
import { Resolve, ActivatedRouteSnapshot, Router } from "@angular/router";
import { SeoService } from '@shared/services/common.service';
@Injectable({ providedIn: 'root' })
export class HomePageRouterResolverService implements Resolve<any> {
    rootUrl = 'https://example.com';
    constructor(private _seoService: SeoService ) { }
    resolve(activatedRouteSnapshot: ActivatedRouteSnapshot) {
        let seoData: any    = {};
        seoData['title']    = "Home page Title";
        seoData['feature_image'] = this._seoService.cdn_url + "features.jpg"; 
        seoData['description']     = "Home page description";
        seoData['keywords'] = "Terms and Conditions";
        let curl = activatedRouteSnapshot['_routerState']['url'];
        seoData['curl']     = rootUrl + curl;
        this._seoService.setAdMetaData(seoData);
        return true;
    }
}

How to Set canonical URL in Angular service

import { Injectable, ComponentFactoryResolver, Inject, RendererFactory2, Renderer2 } from '@angular/core';
import { MatSnackBar } from '@angular/material/snack-bar';
import { Overlay, OverlayRef } from '@angular/cdk/overlay';
import { LoadingComponent } from '../components/loading/loading.component';
import { SnackBarComponent } from '../components/snack-bar/snack-bar.component';
import { ComponentPortal } from '@angular/cdk/portal';
import { HttpClient } from '@angular/common/http';
import { Title, Meta } from '@angular/platform-browser';
import { DOCUMENT } from '@angular/common';
import { environment } from '@env/environment';
@Injectable({
    providedIn: 'root'
})
export class SeoService {
    public copyrightYear: any = '2021';
    private renderer: Renderer2;
    public geoLocationDetails: any = {};
    public ipAddress: any = {};
    constructor(private http: HttpClient, private titleService: Title, private metaService: Meta, @Inject(DOCUMENT) private dom: any, rendererFactory: RendererFactory2) {
        let d = new Date();
        this.copyrightYear = d.getFullYear();
        this.renderer = rendererFactory.createRenderer(null, null);
        this.getIpInfo();
    }  
   updateCanonicalUrl(url: string) {
        const head = this.dom.getElementsByTagName('head')[0];
        var element: HTMLLinkElement = this.dom.querySelector(`link[rel='canonical']`) || null
        if (element == null) {
            element = this.dom.createElement('link') as HTMLLinkElement;
            head.appendChild(element);
        }
        element.setAttribute('rel', 'canonical')
        element.setAttribute('href', url)
        this.metaService.updateTag({ property: 'og:url', content: url });
    }
   }
}

Github link

  • Comment on this post I will share the link.

Referance


Spread the love
Tagged , , ,

About Chandra

Technology lover. Professionally Software Developer and write some Technical Blog to help newcomer.
View all posts by Chandra →

Leave a Reply

Your email address will not be published.