2

How to access the angular variable tracking ID(UA-123XXXXXX-1) in script tag

<app-root></app-root>
<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', 'UA-123XXXXXX-1', 'auto');// add your tracking ID here.
ga('send', 'pageview');


</script>
3
  • What are you trying to do, I do not understand. Are you trying to add google analytics to your angular application? if so, you don't add angular references there. The script that you added was fine. The rest of the code should e in your bootstrapped component. Appcomponent Commented Aug 13, 2018 at 18:26
  • @TaranjitKang , i want to set this UA-123XXXXXX-1 variable from angular Commented Aug 13, 2018 at 18:32
  • 2
    Possible duplicate of Angular 4+ using Google Analytics Commented Aug 13, 2018 at 18:34

1 Answer 1

3

If you want to do it from Angular then you need to do the whole thing from Angular.

// ga.ts
declare const ga: any;

export function startAnalytics(token) {
  (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', token, 'auto');
  ga('send', 'pageview');
}

// whatever.ts
import { startAnalytics } from './ga.ts';

// here e.g. retrieving your token from backend or whatsoever work
// you want to be done before

startAnalytics('whatever token you want');

Actually I'm not really sure ga('send', 'pageview'); is the thing you want in SPA however this is outside the scope of your question.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, just a little modification this line i[r].l = 1 * new Date(); is throwing the error ERROR in src/app/ga.ts(9,29): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.