13

Is there any way to use Google Adsense ads on an Angular 2 app?

I have seen this Google AdSense ads in Angular 2 components? but the answer isn't actually working for me. I see a blank space instead of my ad. What I'm trying to place is responsive ad. I did exactly as the answer in the above question said, with this template code:

<div class="text-center">
    <ins class="adsbygoogle" style="display:inline-block;height:150px"
    data-ad-client="my ca-pub" data-ad-slot="my ad slot"></ins>
</div>

Any ideas?

pizzaisdavid
  • 455
  • 3
  • 13
TheUnreal
  • 23,434
  • 46
  • 157
  • 277

2 Answers2

16

The answer in this link is worked for me. Even better I managed improve that code which can be use with dynamic Slot info.

banner.component.ts

import { Component, AfterViewInit, Input } from "@angular/core"
@Component({
moduleId: module.id,
selector: "google-adsense",
template: ` <div>
        <ins class="adsbygoogle"
           style="display:block;"
            data-ad-client="write_your_pub_"
    [attr.data-ad-slot]="data"
            data-ad-format="auto"></ins>
         </div>   
            <br>            
  `,

})

export class BannerComponent implements AfterViewInit {
@Input() data;
constructor() {}
ngAfterViewInit() {
setTimeout(() => {
 try {
    (window["adsbygoogle"] = window["adsbygoogle"] || []).push({});
  } catch (e) {
    console.error(e);
  }
}, 2000);
} }

Add this in your html where you want your ad to appear

<google-adsense [data]="your_slot_id"></google-adsense>

Add google adsense script in your main html file

<script async src=//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js>/script>

Don't forget to add app.module.

In the other hand, Google adsense banners doesn't show in localserver and if it's in server it takes time to shown up. you can sure that it's working by changing backup ads property to

Fill space with a solid color 

in Google Adsense portal.

Community
  • 1
  • 1
Levent Üncü
  • 325
  • 2
  • 10
  • 1
    Maybe things have changed since this post; Google AdSense ads do appear in locally-hosted sites. – Bryan Green Jul 25 '17 at 21:47
  • does this still work ? (I come from the future, 2020 where angular 8 and 9 rule the world). – bvdb May 04 '20 at 09:41
  • 1
    @bvdb it works in 2020. The most updated steps as of July,2020 https://stackoverflow.com/a/63045073/4067905 – Keyul Jul 23 '20 at 00:37
  • @Keyul unfortunately, that's angular SSR, (= server-side-rendering, which is a workaround, which basically turns an angular application in a static website. That works great for simple websites, but it's a nightmare for websites which use socket-io to stream real-time data). – bvdb Jul 23 '20 at 09:31
1

This may not be the best answer but I suggest using the module ng2-adsense. From there you can smoothly place the ad via using the HTML tag ng-adsense.

Shan Surat
  • 304
  • 4
  • 13