Created
October 27, 2024 21:31
-
-
Save Mustafa-Omran/9e4f1c6b50a9a5ea15a6afe3d94b0686 to your computer and use it in GitHub Desktop.
Google Tag Manager (GTM) dynamically in Angular
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component, OnInit } from '@angular/core'; | |
import { GoogleTagManagerService } from './google-tag-manager.service'; | |
@Component({ | |
selector: 'app-root', | |
templateUrl: './app.component.html' | |
}) | |
export class AppComponent implements OnInit { | |
constructor(private gtmService: GoogleTagManagerService) {} | |
ngOnInit(): void { | |
this.gtmService.loadGTM(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable, Renderer2, RendererFactory2, Inject } from '@angular/core'; | |
import { DOCUMENT } from '@angular/common'; | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class GoogleTagManagerService { | |
private renderer: Renderer2; | |
private readonly gtmId = 'GTM-XXXXXX'; | |
constructor( | |
rendererFactory: RendererFactory2, | |
@Inject(DOCUMENT) private document: Document | |
) { | |
this.renderer = rendererFactory.createRenderer(null, null); | |
} | |
loadGTM(): void { | |
// Load GTM script | |
const script = this.renderer.createElement('script'); | |
script.async = true; | |
script.src = `https://www.googletagmanager.com/gtm.js?id=${this.gtmId}`; | |
this.renderer.appendChild(this.document.head, script); | |
// Add noscript tag (for when JavaScript is disabled) | |
const noscript = this.renderer.createElement('noscript'); | |
noscript.innerHTML = ` | |
<iframe src="https://www.googletagmanager.com/ns.html?id=${this.gtmId}" | |
height="0" width="0" style="display:none;visibility:hidden"></iframe> | |
`; | |
this.renderer.appendChild(this.document.body, noscript); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment