@hakimio/ngx-google-analytics

中文文档
15.0.0发布于 2023/10/03MITTypeScriptES Module近 30 天下载 7260

A simple Google Analytics wrapper for Angular apps

原始使用文档
文档目录13 节
  1. Setup
  2. Install the package
  3. Standalone app component
  4. NgModule
  5. Setup Router Provider
  6. Advanced Router Provider Setup
  7. GoogleAnalyticsService
  8. Register Analytics events
  9. Manually register page views
  10. Directives
  11. Simple directive usage
  12. Usage on input elements
  13. Directive groups

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>

版本与发布记录

@hakimio/ngx-google-analytics 共发布 1 个版本,首次发布于 2023/10/03;过去 12 个月发布了 0 个版本。

版本发布日期距今
15.0.0latest2023/10/033 年前

关于 @hakimio/ngx-google-analytics 的常见问题

@hakimio/ngx-google-analytics 是什么?

A simple Google Analytics wrapper for Angular apps

如何安装 @hakimio/ngx-google-analytics?

在项目目录运行 npm install @hakimio/ngx-google-analytics,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@angular/common(>=16.0.0)、@angular/core(>=16.0.0)、@angular/router(>=16.0.0)、rxjs(^7.4.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@hakimio/ngx-google-analytics 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@hakimio/ngx-google-analytics 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@hakimio/ngx-google-analytics 可以商用吗?

@hakimio/ngx-google-analytics 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@hakimio/ngx-google-analytics 的下载量有多少?

根据 npm 官方下载统计,@hakimio/ngx-google-analytics 在 2026/10/17 – 2026/11/15 这 30 天内被下载 7,260 次,日均约 242 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@hakimio/ngx-google-analytics 还在维护吗?

最新版本 15.0.0 发布于 2023/10/03(3 年前);至今共发布 1 个版本,其中过去 12 个月发布了 0 个;首次发布于 2023/10/03。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。