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
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.
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
.