How To Add Google Analytics In Angular 4

Web Development Software

Integrating Google Analytics into an Angular 4 app is an effective method for monitoring and evaluating user actions on your website. As a developer with experience in installing Google Analytics in various projects, I am enthusiastic to provide my knowledge and assist you in this procedure.

Getting Started

Before we dive into the technical details, let’s make sure we have everything we need. First, you’ll need a Google Analytics account. If you don’t have one, head over to the Google Analytics website and sign up. Once you have your account, make note of your Tracking ID, which will be in the format UA-XXXXX-X.

Step 1: Install the Google Analytics Package

To add Google Analytics to an Angular 4 project, we’ll be using the angular-google-analytics package. Start by opening your terminal and navigating to your project’s root directory. Run the following command to install the package:

npm install angular-google-analytics

Step 2: Configure the Google Analytics Module

Next, we need to configure the Google Analytics module in our Angular 4 application. Open the app.module.ts file and import the necessary modules:

import { NgxGoogleAnalyticsModule, NgxGoogleAnalyticsRouterModule } from 'angular-google-analytics';

Then, add the following code to the imports array:


Replace ‘UA-XXXXX-X’ with your own Tracking ID.

Step 3: Track Page Views

Now that we have installed and configured the Google Analytics module, we can start tracking page views in our Angular 4 application. Open the app.component.ts file and import the necessary modules:

import { NgxGoogleAnalyticsService } from 'angular-google-analytics';

Next, inject the NgxGoogleAnalyticsService in the constructor:

constructor(private gaService: NgxGoogleAnalyticsService) { }

Finally, add the following code to the ngOnInit method to track page views:


Make sure to replace ‘/’ with the path of your current page if needed.

Step 4: Advanced Tracking and Analytics

Google Analytics provides a wide range of features and options for tracking and analyzing user behavior. Some examples include event tracking, custom dimensions, and ecommerce tracking. I encourage you to explore the Google Analytics developer documentation to learn more about these advanced features and how to implement them in your Angular 4 application.


Adding Google Analytics to an Angular 4 application is a straightforward process that can provide valuable insights into your website’s performance and user behavior. By following the steps outlined in this article, you’ll be able to easily track page views and explore more advanced tracking and analytics options. Happy tracking!