@classi/ngx-google-analytics
TypeScript icon, indicating that this package has built-in type declarations

5.0.0 • Public • Published

@classi/ngx-google-analytics

@classi/ngx-google-analytics はAngularアプリケーションとGoogle Analytics API(gtag.js)間の橋渡しをするためのライブラリです。

機能

  • イベントのトラッキング
  • [clAnalyticsOn] ディレクティブによるDOMイベントのトラッキング

インストール

# install the package
$ npm i @classi/ngx-google-analytics
# install peer dependencies
$ npm i -D @types/gtag.js

使い方

0. gtag.jsのインストール

@classi/ngx-google-analyticswindow.gtag 変数に依存しています。 公式ガイドに従ってgtag.jsをセットアップしてください: https://developers.google.com/analytics/devguides/collection/gtagjs

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag() {
    dataLayer.push(arguments);
  }
  gtag('js', new Date());

  gtag('config', 'GA_MEASUREMENT_ID');
</script>

[!TIP] グローバル関数の名前を変更している場合は、後述のプロバイダー設定で独自の gtagResolver を設定できます。

1. プロバイダーの設定

@classi/ngx-google-analytics の機能を利用するためにアプリケーションへプロバイダーを追加します。

import { ApplicationConfig } from '@angular/core';
import { provideGoogleAnalytics } from '@classi/ngx-google-analytics';

export const appConfig: ApplicationConfig = {
  providers: [
    provideGoogleAnalytics({ /** custom config **/ }),
  ],
};

AnalyticsTrackerConfig オプション

  • disableTracking?: boolean: トラッキングを無効化します。開発環境で利用します。デフォルトでは false です。
  • startTrackingOnInit?: boolean: アプリケーションの初期化時に自動的にトラッキングを開始する。デフォルトでは false です。
  • enableVirtualPageViewTracking?: boolean: ルーターイベントを利用して仮想ページビューをトラッキングする。デフォルトでは false です。
  • gtagResolver?: GtagResolveFn: gtag 関数を解決する関数を指定します。デフォルトでは window.gtag を参照します。

[!WARNING] GA4ではシングルページアプリケーションであっても page_view イベントを自動的に送信するため、基本的には仮想ページビューイベントを使用する必要はありません。 手動でページビューを送る必要がある場合は、2重計測を防ぐために自動ページビュー計測を無効にする必要があります。 自動ページビュー計測を無効化するには、gtag スニペットの config メソッドに send_page_view パラメータを追加します。

gtag('config', 'GA_MEASUREMENT_ID', { send_page_view: false });

詳しくは公式ドキュメントを参照してください: https://developers.google.com/analytics/devguides/collection/ga4/views?hl=ja&client_type=gtag#manual_pageviews

2. トラッキングAPIを利用する

@classi/ngx-google-analyticsAnalyticsTracker クラスを提供します。これを利用してトラッキングを行います。

トラッキングの開始: startTracking()

startTrackingOnInit: trueを設定していれば、このステップは省略できます。

Angularルーターですべてのページビューイベントをトラッキングするには、最初のナビゲーションの前にトラッキングを開始します。通常、トラッキングを開始するのに最適な場所は AppComponent のコンストラクタです。

export class AppComponent {
  constructor(private readonly analytics: AnalyticsTracker) {
    this.analytics.startTracking();
  }
}

ユーザー情報の設定: setUserContext(user) / clearUserContext()

export class AppComponent {
  constructor(private readonly analytics: AnalyticsTracker) {
    this.analytics.startTracking();
  }

  setUserId(userId: string) {
    this.analytics.setUserContext({ id: userId });
    this.analytics.clearUserContext();
  }
}

ユーザープロパティ(カスタムディメンション)の設定: setUserProperties(properties)

export class AppComponent {
  constructor(private readonly analytics: AnalyticsTracker) {
    this.analytics.startTracking();
  }

  someMethod() {
    this.analytics.setUserProperties({
      custom_property: 'value',
    });
  }
}

イベントの送信: sendEvent(event)

export class AppComponent {
  constructor(private readonly analytics: AnalyticsTracker) {
    this.analytics.startTracking();
  }

  sendCustomEvent() {
    this.analytics.sendEvent({
      name: 'click',
      // optional
      params: {
        event_category: 'test',
        event_label: 'foobar',
        value: 100,
      },
    });
  }
}

AnalyticsOnDirective: <button clAnalyticsOn>

単一のDOMイベントとイベントトラッキングをバインドするディレクティブです。GoogleAnalyticsModule をインポートして利用できます。

@Component({
  standalone: true,
  imports: [GoogleAnalyticsModule],
  template: `<button clAnalyticsOn="click" [analyticsEvent]="clickEvent">Buy</button>`,
})
export class SomeComponent {
  clickEvent = {
    name: 'click',
    params: {
      event_category: 'test',
      event_label: 'foobar',
      value: 100,
    },
  };
}
  • clAnalyticsOn="{{eventName}}": トラッキングするDOMイベント名を指定します。
  • [analyticsEvent]="event": Google Analyticsに送信するイベントオブジェクトを設定します。詳細は sendEvent ドキュメントを参照してください。

/@classi/ngx-google-analytics/

    Package Sidebar

    Install

    npm i @classi/ngx-google-analytics

    Weekly Downloads

    130

    Version

    5.0.0

    License

    none

    Unpacked Size

    114 kB

    Total Files

    29

    Last publish

    Collaborators

    • classi-dev