0
votes

I'm using google tag manager(GTM) to manage tags in the angular application like this:

<html lang="en">
  <head>
    <base href="/">
    <title>Angular Tour of Heroes</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Google Tag Manager -->
    <script>(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','GTM-WAHOCA');</script>
    <!-- End Google Tag Manager -->
  </head>
  <body>
    <!-- Google Tag Manager (noscript) -->
    <noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-WAHOCA"
      height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
    <!-- End Google Tag Manager (noscript) -->
    <my-app>Loading...</my-app>
  </body>
</html>

Now I'd like to use different GTM containers according to the environments, like development, production environment and so on. The above code is just using the 'GTM-WAHOCA' container ID by hardcoding.
How can I configure to use different GTM containers according to the environments in the index.html? That means I want to mangage the GTM container IDs conveniently in the file. Or, are there other ways to achieve my requirements?

References:
1.Is there a way to conditionally include scripts in index.html as in analytics?
2.Conditional template logic in index.html for beta.11-webpack
3.Feature Request: load scripts in angular-cli.json conditionally?

3
Not sure what the problem is exactly, but you can add a script tag like shown in stackoverflow.com/questions/34140065/…. Instead of elementRef.nativeElement just use document.headGünter Zöchbauer

3 Answers

0
votes

I made a similar question a couple weeks ago, I thing it could be valid for here!

document.getElementById("myScript").remove();
var testScript = document.createElement("script");
testScript.setAttribute("id", "myScript");
testScript.setAttribute("src", "assets/js/script.js");
document.body.appendChild(myScript);
0
votes

main.ts:

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

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

if (env.production) {

  // add Google Analytics script to 

<head>
  const script = document.createElement('script');
  script.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','GTM-XXXXXXX');`;

  document.head.appendChild(script);


  // disable Angular development mode

  enableProdMode();
}