Injecting Ad Units in Angular 18 Applications: A Complete Guide

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

Understanding the Challenge

Unlike traditional websites, single-page applications (SPAs) dynamically load content on the same page when routes change, instead of reloading the entire page. 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: Adding the AdSense Script

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: Generating the Ad Component

Next, create a dedicated component for your ad unit by running the following command:

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

Step 3: Building the Ad Component

Here’s a step-by-step breakdown of how to build the ad component:

  1. Place the <ins> tag of your ad unit in the component's template.
  2. Wait for the view to initialize by implementing AfterViewInit.
  3. Inject the script that pushes the ad unit into the ad collection.
  4. To avoid duplication, implement OnDestroy and remove the script when navigating away from the route.

Ad Component Code

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 for the script element

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

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

Bonus: Generating Unique IDs

Here’s a utility function to generate unique IDs for your ad scripts:

export function generateRandomString(length: number): string {
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let result = '';
  for (let i = 0; i < length; i++) {
    const randomIndex = Math.floor(Math.random() * characters.length);
    result += characters.charAt(randomIndex);
  }
  return result;
}

Step 4: Using the Ad Component

To use the ad component, import it into your Angular module and include the selector in your templates:

<app-vertical-ad-responsive></app-vertical-ad-responsive>

With this setup, you can seamlessly integrate Google AdSense ad units into your Angular 18 single-page application. Enjoy increased monetization opportunities without compromising on user experience!


Last updated

Comments

Leave a Comment