在Angular8开发的网站部署Google广告

Google广告代码是包含script代码的,如果直接复制Google广告到Angular的html页面上,编译时是会去除掉script标签代码,具体可看这个GitHub文章:传送门

新建component

  • component的template写上google广告的代码,不包含script标签的代码,如下:
  1. template: `<div>
  2. <ins class="adsbygoogle"
  3. style="display:block"
  4. data-ad-client="ca-pub-xxxxxxx"
  5. data-ad-slot="xxxxx"
  6. data-ad-format="auto"
  7. data-full-width-responsive="true"></ins>
  8. </div>`
  • init方法初始化window.adsbygoogle
  1. ngAfterViewInit() {
  2. try{
  3. (window['adsbygoogle'] = window['adsbygoogle'] || []).push({});
  4. }catch(e){
  5. console.error("error");
  6. }
  • 完整代码
  1. import { Component, AfterViewInit} from '@angular/core';
  2. // <!-- tools网站纪念日计算横幅广告 -->
  3. @Component({
  4. selector: 'app-commemoration-ad',
  5. template: `<div>
  6. <ins class="adsbygoogle"
  7. style="display:block"
  8. data-ad-client="ca-pub-xxxxxxx"
  9. data-ad-slot="xxxxx"
  10. data-ad-format="auto"
  11. data-full-width-responsive="true"></ins>
  12. </div>`
  13. })
  14. export class CommemorationAdComponent implements AfterViewInit {
  15. constructor() { }
  16. ngAfterViewInit() {
  17. try{
  18. (window['adsbygoogle'] = window['adsbygoogle'] || []).push({});
  19. }catch(e){
  20. console.error("error");
  21. }
  22. }
  23. }

html引入模块

  1. <!--在您希望展示广告的html中添加此内容-->
  2. <app-commemoration-ad></app-commemoration-ad>

index.html引入js文件

  1. <script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

注意

如果是定义的公共模块,需要在模块里面申明