Igor Simic
4 years ago

How to add Google ads to your Angular page




Adding Google Adsense ads to your Angular application can be done by creating directive and loading (async) adsbygoogle.js script. The nature of Angular is to change the content of the page without reloading which could be problem for Google ads. 

On route change, or loading another page within Angular, Google ads could stop working and you could get error 400:
ads Failed to load resource: the server responded with a status of 400

To fix this we have to create directive which will tackle this  problem. But first, inside your index.html page include async adsbygoogle.js script

<!-- Google Ad Script -->
     <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

Next, we will create directive:
app.directive('adsense', ['$timeout', function($timeout) {
        return {
            restrict: 'E',
            replace: true,
            scope : {
                adStyle : '@',
                adFormat : '@',
                adLayout : '@',
                layoutKey : '@',
                adClient : '@',
                adSlot : '@',
                
            },
            template: '<div class="ads"><ins class="adsbygoogle" style="{{adStyle}}" data-ad-format="{{adFormat}}"  data-ad-layout="{{adLayout}}" data-ad-layout-key="{{layoutKey}}" data-ad-client="{{adClient}}" data-ad-slot="{{adSlot}}" data-ad-region="page-'+Math.random()+'"></ins></div>',
            
            link: function(scope,element,attr){
              return $timeout(function(){
                return (adsbygoogle = window.adsbygoogle || []).push({});
              });
            }
        };
    }]);

The trick which will prevent you from getting status 400 from Google is inside of template param. We have added additional parameter and assigned random value to it:
data-ad-region="page-'+Math.random()+'"

And now, we can use this directive like this:
<adsense ad-style="display:block;border:0px" ad-format="fluid" ad-layout="text-only" layout-key="-hs-1p+4m-15-5j" ad-client="ca-pub-123456789" ad-slot="123456789"></adsense>

Also it is ver important to set min width and height of ads container:
adsense{
   min-height: 90px; 
  width: 100%; 
  text-align: center;

}


ins {
    min-width: 300px;
    min-height: 90px;
    width:100%;
}

to prevent Google ads errors you can also wrap directive 
                return (adsbygoogle = window.adsbygoogle || []).push({});

 method in try/catch:
try{
 (adsbygoogle = window.adsbygoogle || []).push({});
}catch(ex){}



More info and similar solutions can be found here: