Event Tracking With Google Analytics in Angular
Event tracking is a great way to track user behavior in your application and it doesn’t require much effort to implement. Assuming your application was scaffolded using the Angular ng-cli tool, you can add an attribute directive to your application that will send click events to your Google Analytics in just a few minutes.
Add Google Analytics
To implement event tracking in your Angular application, you first need to add Google Analytics. You may use the following Google Analytics debug script. That script outputs all your Google Analytics events to the console. For production, you may want to use the production Google Analytics script that does not do that.
Create Directive
Next step is to create an attribute directive. Using the ng-cli tool, run the following :
ng generate directive button
This will create a directive as well as update the app.module.ts file. Inside that directive, add the following code snippet.
That code snippet creates an attribute directive that can be added to any element tag that you want to track clicks on. Here is an example how to use it
Checking Google Analytics
Once you created the event tracking directive, attach it to a tag, launch the application and click on that tag. Your Google Analytics should have caught the event.