Google Analytics Angular Service with Click Events

This example will give your Angular application the ability to use gtag() and use the service to inject it in components needing Google Analytics push abilities such as events.

seo.service.ts

import { Injectable } from '@angular/core';
import { Meta, Title } from '@angular/platform-browser';

declare var gtag: Function;

@Injectable()
export class SeoService {
    constructor(
        private titleService: Title, 
        private metaService: Meta
    ) {}

    /**
     * Page title.
     * @param strTitle - Page title.
     */
    public setTitle(strTitle: string) {
        this.titleService.setTitle(strTitle);
    } // setTitle()

    /**
     * Sets the meta description.
     * @param strMetaDescription - Meta description.
     */
    public setMetaDescription(strMetaDescription: string) {
        this.metaService.updateTag({
            content: strMetaDescription
        }, "name='description'" );
    } // setMetaDescription()

    /**
     * Sends Google the click event.
     * @param strCategory - Set category.
     * @param strName - Description
     */
    public handleOutboundLinkClicks(strCategory, strDescription) {
        gtag('event', 'click', {
            "event_category": strCategory,
            "event_label": strDescription
        });
    } // handleOutboundLinkClicks()
}

Function Descriptions

  • setTitle(strTitle: string) – Sets the title of the page displayed.
  • setMetaDescription(strMetaDescription: string) – Sets the meta description.
  • handleOutboundLinkClicks(strCategory, strDescription) – Push to Google Analytics a click event.

example.component.ts

import { Component } from '@angular/core';
import { SeoService } from "./seo.service";

@Component({
    selector: 'duaneleem-example',
    template: ``,
    styles: [``],
    providers: [SeoService]
})
export class ExampleComponent {
    handleOutboundLinkClicks: any;

    constructor(private seoService: SeoService) {
        // SEO
        seoService.setTitle("DuaneLeem.com");
        seoService.setMetaDescription("The Perpetual Student");
        this.handleOutboundLinkClicks = seoService.handleOutboundLinkClicks;
    }
}

Hope this helps!  If there are much efficient ways to better do this, please let me know 🙂

~ Duane

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: