title: Angular 4+ using Google Analytics
body: <p>I'm trying to use the Google Analytics with angular 4, but i can't find any @type to ga.js in ts.</p>
  
  <p>For a quick solution I used this in every component:</p>
  
  <pre><code>declare let ga: any;
  </code></pre>
  
  <p>Following how I resolved it:</p>
  
  <p>Create a function to load the GA dynamically that inserts the GA script with current trackingId and user.</p>
  
  <pre><code>    loadGA(userId) {
          if (!environment.GAtrackingId) return;
  
          let scriptId = 'google-analytics';
  
          if (document.getElementById(scriptId)) {
              return;
          }
  
          var s = document.createElement('script') as any;
          s.type = "text/javascript";
          s.id = scriptId;
          s.innerText = "(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','//www.google-analytics.com/analytics.js','ga');ga('create', { trackingId: '" + **environment.GAtrackingId** + "', cookieDomain: 'auto', userId: '" + **userId** + "'});ga('send', 'pageview', '/');";
  
          document.getElementsByTagName("head")[0].appendChild(s);
      }
  </code></pre>
  
  <p>Create the service to implement the methods that you will need.</p>
  
  <pre><code>import { Injectable } from '@angular/core';
  import { environment } from '../../../environments/environment';
  
  declare let ga: any;
  
  @Injectable()
  export class GAService {
      constructor() {
      }
  
      /**
       * Checks if the GA script was loaded.
       */
      private useGA() : boolean { 
          return environment.GAtrackingId &amp;&amp; typeof ga !== undefined;
      }
  
      /**
       * Sends the page view to GA.
       * @param  {string} page The path portion of a URL. This value should start with a slash (/) character.
       */
      sendPageView(
          page: string
      ) {
          if (!this.useGA()) return;
          if (!page.startsWith('/')) page = `/${page}`;      
          ga('send', 'pageview', page);
      }
  
  
      /**
       * Sends the event to GA.
       * @param  {string} eventCategory Typically the object that was interacted with (e.g. 'Video')
       * @param  {string} eventAction The type of interaction (e.g. 'play')
       */
      sendEvent(
          eventCategory: string,
          eventAction: string
      ) { 
          if (!this.useGA()) return;
          ga('send', 'event', eventCategory, eventAction);
      }
  }
  </code></pre>
  
  <p>Then I finally use the service injected in component.</p>
  
  <pre><code>constructor(private ga: GAService) {}
  
  ngOnInit() { this.ga.sendPageView('/join'); }
  </code></pre>