首页 > 解决方案 > 如何在 Angular 模板中嵌入 GitHub 要点?

问题描述

Angular 会忽略script其模板中的标签,但它们是加载 GitHub gist 所必需的。这样做的最佳做法是什么?使用iframe? 动态创建script标签?或者是其他东西?

标签: javascriptangulargithubembeddinggist

解决方案


一种方法是在内部创建一个iframewithscript并在您希望您的要点出现时附加它(基于jasonhodges解决方案)。

模板

 <iframe #iframe type="text/javascript"></iframe> 

零件

@ViewChild('iframe') iframe: ElementRef;

gistUrl: string;

ngAfterViewInit() {
  const doc = this.iframe.nativeElement.contentDocument || this.iframe.nativeElement.contentElement.contentWindow;
    const content = `
        <html>
        <head>
          <base target="_parent">
        </head>
        <body>
        <script type="text/javascript" src="${this.gistUrl}"></script>
        </body>
      </html>
    `;
    doc.open();
    doc.write(content);
    doc.close();
}

推荐阅读