Using Google Adsense ads on Angular 2 application

后端 未结 2 1265
广开言路
广开言路 2021-01-31 22:09

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 m

相关标签:
2条回答
  • 2021-01-31 22:40

    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.

    0 讨论(0)
  • 2021-01-31 23:03

    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.

    0 讨论(0)
提交回复
热议问题