npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@hakimio/ngx-google-analytics

v15.0.0

Published

A simple Google Analytics wrapper for Angular apps

Downloads

6,074

Readme

Ngx Google Analytics

A simple way to track GA4 events in Angular apps.

@hakimio/ngx-google-analytics is a fork of Max Andriani's ngx-google-analytics.

Index

Setup

Install the package

npm install @hakimio/ngx-google-analytics

Standalone app component

If your app component is using standalone API, follow these steps to set up the library:

  • Add provideGoogleAnalytics('ga4-tag-id') to your app's providers. If you can not find your GA4 tag id, see this Google help page.

main.ts

import {AppComponent} from './app/app.component';
import {bootstrapApplication} from '@angular/platform-browser';
import {ROUTES} from './app/app.routes';
import {provideGoogleAnalytics} from '@hakimio/ngx-google-analytics';

bootstrapApplication(AppComponent, {
    providers: [
        provideRouter(ROUTES),
        provideAnimations(),
        provideGoogleAnalytics('ga4-tag-id') // ⬅️ Google Analytics provider
    ]
}).catch(err => console.error(err));

You can also specify additional settings using the second optional parameter: provideGoogleAnalytics('ga4-tag-id', settings). See IGoogleAnalyticsSettings interface for more information about available settings.

  • Add NgxGoogleAnalyticsModule to your app component's imports:

app.component.ts

import {NgxGoogleAnalyticsModule} from '@hakimio/ngx-google-analytics';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    standalone: true,
    imports: [
        NgxGoogleAnalyticsModule // ⬅️ Google Analytics module
    ]
})
export class AppComponent {}

NgModule

If your application is NgModule based, follow these steps to set up the library:

  • Add NgxGoogleAnalyticsModule to your root app module's (AppModule) imports.
  • Add provideGoogleAnalytics('ga4-tag-id') in your app module's providers. If you can not find your GA4 tag id, see this Google help page.

app.module.ts

import {NgxGoogleAnalyticsModule, provideGoogleAnalytics} from '@hakimio/ngx-google-analytics';

@NgModule({
    declarations: [
        AppComponent
    ],
    imports: [
        BrowserModule,
        NgxGoogleAnalyticsModule // ⬅️ Google Analytics module
    ],
    providers: [
        provideGoogleAnalytics('ga4-tag-id') // ⬅️ Google Analytics provider
    ],
    bootstrap: [AppComponent]
})
export class AppModule {}

You can also specify additional settings using the second optional parameter: provideGoogleAnalytics('ga4-tag-id', settings). See IGoogleAnalyticsSettings interface for more information about available settings.

Setup Router Provider

If you are using Angular Router and would like to track page views, you can include provideGoogleAnalyticsRouter() in your root app providers.

IMPORTANT: provideGoogleAnalyticsRouter() is not compatible with SSR and should not be included in server app providers.

import {NgxGoogleAnalyticsModule, provideGoogleAnalytics, provideGoogleAnalyticsRouter} from '@hakimio/ngx-google-analytics';

@NgModule({
    imports: [
        // ...
        NgxGoogleAnalyticsModule // ⬅️ Google Analytics module
    ],
    providers: [
        provideGoogleAnalytics('ga4-tag-id'),
        provideGoogleAnalyticsRouter() // ⬅️ Google Analytics router provider
    ]
})
export class AppModule {}

Advanced Router Provider Setup

You can include or exclude some routes by passing options object to provideGoogleAnalyticsRouter(options).

Following path matches are supported:

  • Simple path match: { include: [ '/full-uri-match' ] };
  • Wildcard path match: { include: [ '*/public/*' ] };
  • Regex path match: { include: [ /^\/public\/.*/ ] };
import {NgxGoogleAnalyticsModule, provideGoogleAnalytics, provideGoogleAnalyticsRouter} from '@hakimio/ngx-google-analytics';

@NgModule({
    imports: [
        // ...
        NgxGoogleAnalyticsModule // ⬅️ Google Analytics module
    ],
    providers: [
        provideGoogleAnalytics('ga4-tag-id'),
        provideGoogleAnalyticsRouter({ // ⬅️ Google Analytics router provider
            include: ['/some-path'],
            exclude: ['*/another/path/*']
        })
    ]
})
export class AppModule {}

GoogleAnalyticsService

The service provides strongly typed way to call gtag() command. Apart from type checking, it does not do any other validation or transformation of the parameters.

Register Analytics events

@Component()
export class TestFormComponent {

    private readonly gaService = inject(GoogleAnalyticsService);

    onUserInputName() {
        this.gaService.event('enter_name', {
            category: 'user_register_form',
            label: 'Name',
            options: {
                customDimension: 'foo_bar'
            }
        });
    }

    onUserInputEmail() {
        this.gaService.event('enter_email', {
            category: 'user_register_form',
            label: 'Email'
        });
    }

    onSubmit() {
        this.gaService.event('submit', {
            category: 'user_register_form',
            label: 'Enviar' 
        });
    }

}

Manually register page views

@Component()
export class TestPageComponent implements OnInit {

    private readonly gaService = inject(GoogleAnalyticsService);

    ngOnInit() {
        this.gaService.pageView('/test', {
            title: 'Test the Title'
        });
    }
    
    onUserLogin() {
        this.gaService.pageView('/test', {
            title: 'Test the Title',
            options: {
                user_id: 'my-user-id'
            }
        });
    }

}

Directives

Directives provide a simple way to register Analytics events. Instead of manually using GoogleAnalyticsService, you can simply add ga* attributes to your html elements.

Simple directive usage

By default, the directive calls gtag() on click events, but you can also specify other events by providing gaBind attribute.

IMPORTANT: Remember to import NgxGoogleAnalyticsModule in all your standalone components and modules where you use ga* directives.

<div>
  <button gaEvent="click_test" gaCategory="ga_directive_test">Click Test</button>
  <button gaEvent="focus_test" gaCategory="ga_directive_test" gaBind="focus">Focus Test</button>
  <button gaEvent="blur_test" gaCategory="ga_directive_test" gaBind="blur">Blur Test</button>
  <button gaEvent="custom_test" gaCategory="ga_directive_test" gaBind="customEvent">Custom Event Test</button>
</div>

Usage on input elements

When gaEvent directive is used on form elements, the default trigger is focus event.

<div>
  <input gaEvent="fill_blur" gaCategory="ga_directive_input_test" placeholder="Auto Blur Test"/>
</div>

Directive groups

The gaCategory directive can be specified on higher level of html element group to specify same category for all child elements.

<div gaCategory="ga_test_category">
  <button gaEvent gaAction="click_test">Click Test</button>
  <button gaEvent gaAction="focus_test" gaBind="focus">Focus Test</button>
  <button gaEvent gaAction="blur_test" gaBind="blur">Blur Test</button>
</div>