Search code examples
javascriptangulargithubembeddinggist

How to embed a GitHub gist in the Angular template?


Angular ignores script tags in its template, but they are required to load GitHub gist. What is the best practice to do this? Using iframe? Creating script tag dynamically? Or something else?


Solution

  • One method is to create an iframe with script inside and append it whenever you want your gist to appear (based on jasonhodges solution).

    Template

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

    Component

    @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();
    }