I'm trying to load some Responsive ads in an AdComponent
in my app. The component is dead simple:
import { Component } from '@angular/core';
import { FORM_DIRECTIVES, CORE_DIRECTIVES } from '@angular/common';
@Component({
selector: 'ad',
templateUrl: 'app/views/ad.html',
directives: [ FORM_DIRECTIVES, CORE_DIRECTIVES ]
})
export class AdComponent {}
ad.html
:
<div class="demo-card-wide mdl-card mdl-shadow--2dp ad-card">
<div class="mdl-card__supporting-text">
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-0123456789"
data-ad-slot="0123456789"
data-ad-format="rectangle, horizontal"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
</div>
I'm finding that these script tags don't make it into the UI and this seems to be a purposeful decision.
I might be able to move around some of the code such as the js reference into the head of my index.html and the window.adsbygoogle
part into the component constructor but I'm not sure if these kinds of modifications are allowed or if there's a better alternative to get these ads to work in Angular 2.
Does anybody have any experience with Google's Adsense ads working in Angular 2? Is there a different, proper way to do this?
This is working for me:
TopBannerComponent.ts ==>
import {Component,OnInit,AfterViewInit} from '@angular/core'
@Component({
moduleId: module.id,
selector: 'google-adsense',
template: ` <div>
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-XXXXXXXXXXXXXX"
data-ad-slot="8184819393"
data-ad-format="auto"></ins>
</div>
<br>
`,
})
export class TopBannerComponent implements AfterViewInit {
constructor() {
}
ngAfterViewInit() {
setTimeout(()=>{
try{
(window['adsbygoogle'] = window['adsbygoogle'] || []).push({});
}catch(e){
console.error("error");
}
},2000);
}
}
Add this in your html where you want your ad to appear
<google-adsense></google-adsense>
Add google adsense script in your main html file
<script async src=//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js></script>