Reputation: 73
I have some Google Analytics code that is outside of the Angular project. I only want to include it if the environment is production.
I know there is an environment variable inside the Angular project that you can reference like this inside typescript...
if (environment.production) {
// do stuff
}
That doesn't help if there is some static code outside of Angular though. I tried putting the Google analytics code inside Angular, but that seems to have issues with the scope not being found and typescript didn't like it.
Right now the best solution I have is to manually check the hostname which probably isn't the best solution (this is in the index.html outside the angular app)...
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-00000000-0"></script>
<script>
if(location.hostname === "productionurl.com") {
// insert google analytics tracking code
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-000000000-0');
}
</script>
I am used to using web.config files which would be simple, but this project uses an angular config instead to deal with environment variables.
Maybe there is a way to get the environment from something like "getAllAngularRootElements()" in vanilla javascript, but I haven't found a way.
Upvotes: 2
Views: 1920
Reputation: 633
For me the most clean solution at the moment is to use a second index.html
file, for example index.prod.html
, and make it replace the original one during the build process by using the "fileReplacements"
property in the "production"
env config inside angular.json
.
Check here: https://github.com/angular/angular-cli/wiki/stories-application-environments
UDPATE for angular 8+
While building, "fileReplacements"
will not work for replacing the index.html
- use "index"
instead:
"index": {
"input": "src/index.prod.html",
"output": "index.html"
},
More info here: https://github.com/angular/angular-cli/issues/14599
Upvotes: 8
Reputation: 110
Did you try setting up Google Analytics through Angulartics (https://github.com/angulartics/angulartics)? That should resolve your problem I think.
Upvotes: 0