How to Inject Google Ads Using an Angular Directive
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
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, which define views and application logic.
- Attribute directives, which modify the look or behavior of existing elements (e.g., applying styles or handling events).
- Structural directives, which change the layout by adding or removing elements from the DOM (*ngIf, *ngFor).
Directives are used to create reusable and dynamic components, manipulate element styles, handle user interactions, and control the structure of the user interface efficiently.
Directive Code
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 details on generating a random string for IDs.
HTML Template
Use the following HTML template in your components where you want to display the ads. The directive appAd will replace the with the ad 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>
You can also create specific components for your ads. The directive will inject the script directly into the ad component, so it does not matter which other component loads the ad component.
Why This Method is Better
- Policy Compliance: By dynamically injecting the ad script using a directive, you reduce the risk of violating Google’s policies.
- Performance: Ads are loaded only when necessary, optimizing performance for users who do not interact with certain parts of your SPA.
- Reusability: The directive can be reused across different components, simplifying your codebase.
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!
Leave a Comment