Google Adsenseコードの取得
Google Adsenseから広告コードを取得します。
サンプルの広告コード
1 2 3 4 5 6 7 8 9 10 |
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <!-- sample --> <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-[ここは変わる]" data-ad-slot="[ここは変わる]" data-ad-format="auto"></ins> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script> |
Google Adsenseコンポーネントの作成
コンポーネント名は任意です。
1 |
ng g component google-adsense |
作成したgoogle-adsenseコンポーネントを下記のようにします。devModeを用意して開発時はGoogle Adsenseはテストモードにしています。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import { Component, isDevMode } from '@angular/core'; @Component({ selector: 'google-adsense', templateUrl: 'google-adsense.html' }) export class GoogleAdsenseFooterComponent { devMode = true; constructor() { this.devMode = isDevMode(); } ngAfterViewInit() { try { (window['adsbygoogle'] = window['adsbygoogle'] || []).push({}); } catch (e) { } } } |
templateは下記の通りです。ngif
でテストモードかリリースモードかを切り替えています。insタグ内は最初に取得したコードを使用します。insにadtest=”on”がある場合テストモードになります。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<div style='text-align: center'> <ng-container *ngIf="devMode"> <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-[ここは変わる]" data-ad-slot="[ここは変わる]" data-ad-format="auto" adtest="on"></ins> </ng-container> <ng-container *ngIf="!devMode"> <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-[ここは変わる]" data-ad-slot="[ここは変わる]" data-ad-format="auto"></ins> </ng-container> </div> |
スクリプトの読み込み
index.htmlにadsenseのスクリプトを読み込むようにします。
1 2 3 4 |
<head> <!-- 色々 --> <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> </head> |
DI
トップからDIするならapp.module.tsにDIします。
1 2 3 4 5 6 7 8 |
import { GoogleAdsenseComponent } from '../[何処かの]/google-adsense'; // 略 declarations: [ // 色々 // 色々 GoogleAdsenseComponent ], |
使い方
表示したいコンポーネントのtemplateにセレクタを記載するだけです。
1 |
<google-adsense></google-adsense> |