Tracking first click only in Angular

I have tracking on my button that tracks every time it has been clicked. How do I get this to work so that the tracking call gets called only on the first click and no other clicks. Any help on this would be greatly appreciated.

.TS File

public reset(): void {
   this.myTrackingService.submitAnalyticsCall(new MyAnalyticsModel(
        APP-CONSTANTS.destination.myaccount));
}

HTML

<div *ngIf="showMyFilter" class="my-filter--container">
<my-filter(selectReset)="onReset()"></my-filter></div>

28 thoughts on “Tracking first click only in Angular”

  1. If you are fine with your method being called again after a refresh or if you open a new tab then you can create a flag for this.

    public clicked: boolean = false;
    
    public reset(): void {
        if (!this.clicked) {
            this.myTrackingService.submitAnalyticsCall(new MyAnalyticsModel(
                 APP-CONSTANTS.destination.myaccount));
            this.clicked = true;
        }
    }
    
    Reply
  2. You can utilize the RxJS exhaustMap instead which maps to inner observable, ignore other values until that observable completes

    Attached herewith is the Stackblitz Demo for your reference.
    Inside this demo, no matter how many times you click the button, it will only process the 1st instance it got clicked, when the service finishes processing the request, it will be back and open for clicks again

    click$: Subject<boolean> = new Subject<boolean>();
    
    
    ngOnInit(): void {
       this.click$
          .pipe(exhaustMap(() => this.trackService.reset()))
          .subscribe(response => console.log(response));
    }  
    

    NOTE:

    exhaustMap is good for the following scenario as per from Brian Troncone RxJS course:

    1. Ignores emitted values when there is an active inner observable
    2. Use when quick, subsequent emissions can be ignored, like a refresh button or login request
    3. Avoid using this if cancellation is important, or ignoring emissions from the source would cause undesired effects

    – More Examples:
    https://www.learnrxjs.io/learn-rxjs/operators/transformation/exhaustmap

    Reply
  3. A simple way would be to track the clicks in a local variable:

    public reset(): void {
       let clicked = false;
       if(!clicked) {
          this.myTrackingService.submitAnalyticsCall(new MyAnalyticsModel(
            APP-CONSTANTS.destination.myaccount));
          clicked = true;
       }
    }
    

    A more elaborate way would be to do that with RxJs by creating a stream/observable from a click event and then using the take(1) operator, but that would be an overkill for this purpose.

    Either way, the state of the click will be reset when the component or page gets refreshed.

    Reply

Leave a Comment