Engineer's Way

主にソフトウェア関連について色々書くブログです。

Angular4で開発した複数環境のSPAに、それぞれ別のGoogleタグマネージャーのスニペットを設定する方法

 

背景

本番環境と検証環境で運用しているAngular4で作ったSPAに、Googleタグマネージャー(GTM)のコードを埋め込むことになりました。

Googleタグマネージャーとは

f:id:matsnow:20170929004023p:plain

Googleタグマネージャー自体の概要や使い方は以下が参考になります。

www.h-nanae.com

www.milab-inc.com

埋め込み手順

埋め込む必要のある環境が本番環境だけであれば、単にGTMが吐き出してくれたスニペットをそのままindex.htmlに書けばいいわけですが、検証環境にも別のコンテナのスニペットを埋め込みたいとなった時に、少し詰まりました。

というのも、スニペットはheadタグの中とbodyタグ直下にそれぞれ埋め込む必要があるので、app-rootの外にあるindex.htmlに何とかして環境変数を反映させないといけないからです。

とりあえず、少し考えて、実際に試したのが以下のやり方です。

1) environment.tsへの追記

environment.prod.tsなど、各環境用の定義ファイルに

environment: {
    production: true,
    googleTagManager: 'GTM-XXXX'
};

みたいに書いておきます。(GTM-XXXXのところは GTMのコンテナIDを記述)

2) main.tsにスニペット埋め込み用のコードを記述

main.tsのif (environment.production) の中に以下を追記します。
本来、コンテナのIDが入っている箇所は、テンプレート記法で環境変数に置き換えています。

if (environment.production) {
  enableProdMode();

  /////////////// ここから //////////////////
  const script = document.createElement('script');
  script.text = `
  (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
  new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
  j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
  'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
  })(window,document,'script','dataLayer','${environment.googleTagManager}');`;
  document.head.appendChild(script);

  const noscript = document.createElement('noscript');
  const iframe   = document.createElement('iframe');
  iframe.src     = `https://www.googletagmanager.com/ns.html?id=${environment.googleTagManager}`;
  iframe.height  = '0';
  iframe.width   = '0';
  iframe.setAttribute('style', 'display:none;visibility:hidden');
  noscript.appendChild(iframe);
  document.body.insertBefore(noscript, document.body.firstChild);
  /////////////// ここまで //////////////////
}

これで後はGTMのコンソール上でタグやトリガーを設定してやれば、問題なく環境別にアクセス解析をすることができるようになります。
なお、GoogleAnalyticsでも同じ手法が使えるはずです。

あまり実施する必要に迫られることは無さそうなことですが、一応備忘録として。

CloudFormationでElasticSearchService 5.x系を構築する時の注意点

 

CloudFormationでElasticSearchServiceを構築しようとしたところ、
Createに異様に時間がかかる上、

Creating Elasticsearch Domain did not stabilize.

というエラーが出て構築に失敗してしまうという状況に出くわしました。 (ロールバックにも異様に時間がかかるという、、)

調べてみたところ、バージョン5.x系のElasticSearchを作る場合、 AdvancedOptionsの指定が必須らしいとのこと。

https://forums.aws.amazon.com/thread.jspa?messageID=768527

YAMLだとこうなります。

      ElasticsearchVersion: "5.3"
      AdvancedOptions:
        rest.action.multi.allow_explicit_index: true
        indices.fielddata.cache.size: ""

公式ドキュメントだと「Required: No」となっているので結構な罠ですね、、。

AWS::Elasticsearch::Domain - AWS CloudFormation

Angular4(2+)でカスタムValidationを作る

 

Angular4(2+)で独自のValidationを作ってフォームに適用したい時のやり方を調べましたので、備忘録として残しておきます。

1. Validationディレクティブを作成する。

まず、ディレクティブとして、カスタムValidationを実装したクラスを作ります。 以下は単純な例で、フォームへの入力値が「abc」だったらNG、それ以外はOKとしてます。

import { Directive } from '@angular/core';
import { AbstractControl, FormControl, ValidationErrors } from '@angular/forms';

@Directive({
    selector: '[validateCustom][ngModel],[validatorCustom][formControl]'
})

export class CustomValidator {
    check(control: AbstractControl): ValidationErrors|null {
        return control.value === 'abc' ? {‘custom': true} : null;
    }
}

入力をNGとしたい時に「{‘項目名’: true}」をreturnします。

参考:angular.coreのソース
https://github.com/angular/angular/blob/71f5b73296708014b740fb5dd0145c0599de7a19/packages/forms/src/validators.ts

2. 作ったカスタムValidationを使う。

使いたいコンポーネントの中で以下のように書くことで使用できます。

import ‘CustomValidator’ from ‘../directives/custom-validator';

:
onNgInit() {
  const cv = new CustomValidator();
  this.control = new FormControl('', cv.check);
}