Complete guide to inject Google Ad Units in you Angular 18 Application

Learn how to effectively inject Google AdSense ad units into your Angular 18 single-page application with this step-by-step guide.

3 min read •
912 0 1

This article will guide you through the complex process of injecting Google AdSense ad units in your Angular 18 single-page application (SPA).

Understanding the Challenge (Angular SPA + AdSense)

Unlike traditional websites, single-page applications (SPAs) dynamically load content on the same page when routes change, instead of reloading the entire document. This behavior makes the traditional Google AdSense integration ineffective. But don’t worry — this guide will help you successfully implement ad units in Angular SPAs.

Step 1: Add the Google AdSense Script to index.html

To begin, add the AdSense script globally in your index.html file:

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=your_ads_client_id" crossorigin="anonymous"></script>

Step 2: Generate a Dedicated Ad Component

Create a component for your ad unit:

ng g c components/ads/your-ad-unit-type

Step 3: Build the Ad Component (Angular 18)

Here’s a step-by-step breakdown:

  1. Place the <ins> tag of your ad unit in the component template.
  2. Wait for the view to initialize by implementing AfterViewInit.
  3. Inject a script that pushes the ad into the AdSense queue.
  4. Implement OnDestroy to remove the script when navigating away (prevents duplication).

Ad Component Code (TypeScript)

import { AfterViewInit, Component, OnDestroy } from '@angular/core';
import { generateRandomString } from '../../../functions';

@Component({
  selector: 'app-vertical-ad-responsive',
  standalone: true,
  template: `
    <ins class="adsbygoogle" style="display:block"
      data-ad-client="data-ad-client"
      data-ad-slot="data-ad-slot"
      data-ad-format="auto"
      data-full-width-responsive="true"></ins>
  `,
})
export class VerticalResponsiveAdComponent implements AfterViewInit, OnDestroy {
  private scriptId = generateRandomString(10); // Unique ID

  ngAfterViewInit() {
    if (!document.getElementById(this.scriptId)) {
      const script = document.createElement('script');
      script.type = 'text/javascript';
      script.id = this.scriptId;
      script.text = `(adsbygoogle = (window as any).adsbygoogle || []).push({});`;
      document.body.appendChild(script);
    }
  }

  ngOnDestroy() {
    const script = document.getElementById(this.scriptId);
    if (script) {
      document.body.removeChild(script);
    }
  }
}

Bonus: Generate Unique IDs (TypeScript)

Use a simple, URL-safe generator. For stronger randomness in modern browsers, prefer crypto.getRandomValues:

export function generateRandomString(length: number): string {
  const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  const arr = new Uint32Array(length);
  crypto.getRandomValues(arr);
  let out = '';
  for (let i = 0; i < length; i++) {
    out = out + alphabet[arr[i] % alphabet.length];
  }
  return out;
}

Step 4: Use the Ad Component in Templates

Import the component where needed and include it in your templates:

&lt;app-vertical-ad-responsive&gt;&lt;/app-vertical-ad-responsive&gt;

With this setup, you can seamlessly integrate Google AdSense ad units into your Angular 18 SPA — improving monetization without compromising UX.

Comments (1)

MA
mamun_1m January 20, 2025 15:32

Good

Leave a Comment

Replying to someone. Cancel