Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you design and implement an application wide event detection mechanism to capture click events in a large scale Angular application?

I'm trying to implement a solution to report detailed user activities to Google Analytics. Since the application is a single page application I know that I can capture the page change events from router, but this is only the basic part of the solution which is only for reporting seen pages.

Main point is since this is a large scale application containing 500+ pages/components and I don't want to create a logger service requires to change every page by adding it, I need to figure out a way to determine a centralized or application wide place to catch and detect button click events and maybe the pages they are fired from. Then I hope to be able to report detailed user activities on related pages to analytics like X button clicked from Y page.

For a central place I know there are interceptors for HTTP events, and router for page changes. Besides that I know maybe I can use change detection with hooks, but I'm not sure about should I have to work with hooking into application lifecycle level.

How can I implement a mechanism to catch and detect component elements events with related pages in Angular? Are there any best practices or abstractions that framework provides that may I utilize?

Note: I've learned that Google Tag Manager does the job specifically for the analytics purposes, but my question remain same which how to implement it with Angular.

like image 935
Taha Yavuz Bodur Avatar asked Jan 18 '26 08:01

Taha Yavuz Bodur


1 Answers

Custom event API is one option, but you have to despatch that event in all clicks.

So using HostListner we can achieve this.

Add a listener in the main component ie in app.componnet

 @HostListener('window:click', ['$event'])
    onClickEvent(event: MouseEvent) {
    var target = event.target || event.srcElement;
    var id = target['id']; //this will be the id of the target that you clicked
    this.clickedValue = id;

  }

And follow a naming pattern while you adding the id of each item. ie add the component name as the prefix of id. After prod build, the component name will be minified to one-letter name, it loses its original name.

For eg: if you have component mychild.component

<div>
<h1 id="mychild-h1">Test</h1>
</div>

Here, id is myChild-h1 and you can pick the components name from it. Now you have the id and name of the component that you clicked and create a service to log that info.

Attaching one sample code for check

CheckThis

like image 130
Jobelle Avatar answered Jan 19 '26 22:01

Jobelle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!