• Skip to main content
  • Skip to primary sidebar

Web Development Archive

  • Archive
You are here: Home / Other / GTM in Angular

GTM in Angular

environment.ts

import { Environment } from './environment.definitions';

export const environment: Environment = {
googleAnalyticsCode: 'GTM-XXXXXXXX'
};

google-analytics.service.ts

import { Injectable } from '@angular/core';

import { environment } from '../../../environments/environment';

const GTM_SCRIPT_HEAD = 'gtm-script-head';
const GTM_SCRIPT_BODY = 'gtm-script-body';

@Injectable({
providedIn: 'root'
})
export class GoogleAnalyticsService {
public scriptLoaded = false;

public loadScript(): void {
if (document.getElementById(GTM_SCRIPT_HEAD) || !environment.googleAnalyticsCode) {
return;
}
const gtmScriptHead = document.createElement('script');
gtmScriptHead.id = GTM_SCRIPT_HEAD;
gtmScriptHead.innerHTML = `
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','${environment.googleAnalyticsCode}');
`;
document.head.appendChild(gtmScriptHead);

const gtmScriptBody = document.createElement('noscript');
gtmScriptBody.id = GTM_SCRIPT_BODY;
gtmScriptBody.innerHTML = `
<iframe src="https://www.googletagmanager.com/ns.html?id=${environment.googleAnalyticsCode}"
height="0" width="0" style="display:none;visibility:hidden"></iframe>
`;

document.body.appendChild(gtmScriptBody);

this.scriptLoaded = true;
}

public logEvent(eventName: string, eventParams: Record<string, string>): void {
if (!this.scriptLoaded) {
return;
}

// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(window as any).dataLayer = (window as any).dataLayer || [];
// eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(window as any).dataLayer.push({
event: eventName,
...eventParams
});
}

public removeScript(): void {
this._removeScriptById(GTM_SCRIPT_HEAD);
this._removeScriptById(GTM_SCRIPT_BODY);
this._removeGtmLoaderScript();
this.scriptLoaded = false;
}

private _removeScriptById(scriptId: string): void {
const script = document.getElementById(scriptId);
if (!script) {
return;
}

script.remove();
}

private _removeGtmLoaderScript(): void {
const scripts = document.querySelectorAll('script[src^="https://www.googletagmanager.com/gtm.js"]');
scripts.forEach((script) => script.remove());
}
}

app.component.ts

private readonly _ga = inject(GoogleAnalyticsService);
public ngOnInit(): void {
this._ga.loadScript();
...

Filed Under: Other

About Gabor Flamich

I'm a web developer and designer based in Budapest, Hungary. In recent years, I've documented hundreds of solutions I came across during development. This site is an archive for useful code snippets on WordPress, Genesis Framework and WooCommerce. If You have any questions related to WordPress development, get in touch!

Primary Sidebar

  • angular.io
© 2026 WP Flames - All Right Reserved