1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

Run GTM(Google Tag Manager) within Angular SPA

Discussão em 'Angular' iniciado por Unknown developer, Novembro 10, 2024 às 02:13.

  1. I am building an Angular 6 SPA. When using Google Analytics, I am using the following code:

    <script>
    (function(i, s, o, g, r, a, m) {
    i['GoogleAnalyticsObject'] = r;
    i[r] = i[r] || function() {
    (i[r].q = i[r].q || []).push(arguments)
    }, i[r].l = 1 * new Date();
    a = s.createElement(o),
    m = s.getElementsByTagName(o)[0];
    a.async = 1;
    a.src = g;
    m.parentNode.insertBefore(a, m)
    })(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');
    ga('create', 'XXXXXXX', 'auto'); //tracking code


    in index.html Since I want to trigger analytics for every page inside app.component.ts, I have the following code:

    this.router.events.subscribe(event => {
    if (event instanceof NavigationEnd) {
    (window as any).ga("set", "page", event.urlAfterRedirects);
    (window as any).ga("send", "pageview");
    }
    }


    So far, so good. The problem is with Google Tag Manager. Here is the code in index.html:

    <script nonce="1234567890">
    (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.nonce = "1234567890"; j.src =
    '//www.googletagmanager.com/gtm.js?id=' + i + dl; f.parentNode.insertBefore(j, f);
    })(window, document, 'script', 'dataLayer', 'XXXXXXXX');
    </script>


    The above is running only once when Angular bootstraps. I cannot find a similar to the above way as to make it run again when Angular router navigated to another route. Any ideas?

    Continue reading...

Compartilhe esta Página