简体   繁体   中英

Angular Material button click tracking using Google Analytics via Google Tag Manager

I am using the Universal Analytics tag in Google Tag Manager to track user interaction. I want to set up click listeners from within GTM that will fire when certain buttons are clicked on the page. The buttons are Angular Material components.

The issue is that Angular Material puts a wrapper element on top of my button, changing the HTML from this:

<button mat-raised-button type="button" class="blue l" (click)="onContinue()">CONTINUE</button>

to this:

<button _ngcontent-c20="" class="blue l mat-raised-button" mat-raised-button="" type="button">
    <span class="mat-button-wrapper">CONTINUE</span>
    <div class="mat-button-ripple mat-ripple" matripple="" ng-reflect-centered="false" ng-reflect-disabled="false" ng-reflect-trigger="[object HTMLButtonElement]"></div><div class="mat-button-focus-overlay"></div>
</button>

In order to pick up the click events in GTM I have to set the trigger to listen for clicks on the <span> element rather than the <button> element. Thus I loose all identifying information about the button; Any HTML id or class that I use for the <button> is not reflected in the <span> . GTM is unable to distinguish which button was clicked. How can I uniquely identify my button in a way that is visible to GTM?

Note: Identifying the button using the button text (the inner HTML of the <span> ) is not an option since I have multiple buttons on the page with the same text.

I ran into this problem and finally found the solution:

The solution in Google Tag Manager:

Enable Variable-type Click Element.

Create two triggers:

1) Trigger Type: Click-All Elements, Some Clicks, Click ID - equals - "your-id"

2) Trigger Type: Click-All Elements, Some Clicks, Click Element - Matches CSS Selector - "button#your-id span" (see image)

Then in your Tag set two triggers, one to trigger 1, the second to trigger 2.

CSS 选择器配置示例

I would reccommend to use a data attribute to seperate the tracking from other code like this:

<button data-gtm-continue-button>...</buttton>

and use a GTM-Trigger like this: Click Element -> matches CSS selector -> [data-gtm-continue-button], [data-gtm-continue-button] *

In your case if you do not want to use data attibutes you could also just adjust your CSS selector to the following:

button#my-button, button#my-button *

this makes use of the css selector * which means any element within the selector.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM