In my last article, I explained how you can use a component to inject ads into your SPA project. However, after further research, I realized that the solution presented could cause issues if you have auto ads enabled. Additionally, it may violate Google Policies when ads are dynamically added or removed from the DOM.
This article introduces a new solution that uses a directive to replace a part of the code with the ad script. By doing so, this method works just like traditional ad placement, providing a more natural experience and loading scripts only when the user interacts with the interface.
Creating the Directive (Angular 18)
To get started, generate a new directive using the following command:
ng g d directives/ads
This command will create a directive in the app/src/directives directory.
An Angular directive is a class that enhances the behavior or appearance of DOM elements in an Angular application. There are three types:
- Component directives — define views and application logic.
- Attribute directives — modify the look or behavior of existing elements (e.g., styles or events).
- Structural directives — change layout by adding/removing elements (*ngIf, *ngFor).
Directives help you build reusable, dynamic UIs, manipulate styles, handle interactions, and control structure efficiently.
Directive Code (TypeScript)
Below is the code for the directive. You can modify the selector and directive name as needed:
import { AfterViewInit, Directive, ElementRef, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
@Directive({
selector: '[appAd]',
standalone: true
})
export class AdDirective implements AfterViewInit {
constructor(private el: ElementRef, @Inject(DOCUMENT) private document: Document) {}
ngAfterViewInit() {
const hostElement = this.el.nativeElement as HTMLElement;
if (hostElement) {
this.replaceDivWithScript(hostElement);
}
}
private replaceDivWithScript(hostElement: HTMLElement) {
const script = this.document.createElement('script');
script.type = 'text/javascript';
script.id = 'your-random-script-id'; // Use a unique ID to avoid conflicts.
script.text = `(adsbygoogle = window.adsbygoogle || []).push({});`;
const parent = hostElement.parentNode;
if (parent) {
parent.replaceChild(script, hostElement);
}
}
}
Ensure that the script.id
is unique to prevent issues when using multiple ad units on a single page.
You can refer to my
previous article
for generating random IDs.
HTML Template (AdSense Ins + Directive)
Use the following HTML template in your components where you want to display the ads. The directive appAd will replace <div appAd></div> with the ad push script <script>(adsbygoogle = window.adsbygoogle || []).push({});</script>:
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ad-client"
data-ad-slot="ad-slot"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
<div appAd></div>
<head>
).
This keeps your integration compliant and avoids re-adding the loader per component.
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=YOUR_CLIENT_ID" crossorigin="anonymous"></script>
Why This Method Is Better for SPA + SEO
- Policy compliance: Replaces a static placeholder with the official push script, reducing the risk of violating Google’s policies.
- Performance: Loads ads only where needed; avoids extra script tags per component.
- Reusability: The directive is portable across components, simplifying templates.
<ins class="adsbygoogle">
a fixed height on mobile/desktop breakpoints (e.g., utility classes or inline style).
By following this tutorial, you can ensure a smoother and more compliant integration of Google Ads into your Angular Single Page Application. If you have any questions or face issues, feel free to leave a comment below!