Google AdSense ads in Angular 2 components?

前端 未结 4 1163
囚心锁ツ
囚心锁ツ 2020-12-24 09:18

I\'m trying to load some Responsive ads in an AdComponent in my app. The component is dead simple:

import { Component } from \'@angular/core\';
         


        
4条回答
  •  伪装坚强ぢ
    2020-12-24 09:50

    Based on the above solutions I have created a simple solution that can be easy to implement. This solution works with Angular Universal SSR (server side rendering)

    In index.html add script provided from Adsense

      
    

    In component.ts file,

    ngAfterViewInit() {
     try {
       (window['adsbygoogle'] = window['adsbygoogle'] || []).push({});
       
       // If you have two ad on the page, then add this again.
       //(window['adsbygoogle'] = window['adsbygoogle'] || []).push({});
    
    
     } catch (e) {}
    }
    

    In .html file, place ad sense code whenever the ad needs to be displayed.

            

    Update: If ad doesn't show up then, set timeout in component.ts file

        ngAfterViewInit() {
         setTimeout(()=>{
          try {
           (window['adsbygoogle'] = window['adsbygoogle'] || []).push({});
          } catch (e) {}
         },500);
        }
    

    Note: Test your code on registered domain or subdomain. On localhost, the ad will not display.

提交回复
热议问题