Search code examples
javascriptangulariframegoogle-api-js-clientandroid-management-api

How to correctly load and use gapi.iframes library from Angular 9?


I'm trying to add a google api iframe to my project, as described in the Android Management API documentation:

<script src="https://apis.google.com/js/api.js"></script>
<div id="container"></div>
<script>
  gapi.load('gapi.iframes', function() {
    var options = {
      'url': 'https://play.google.com/work/embedded/search?token=web_token&mode=SELECT',
      'where': document.getElementById('container'),
      'attributes': { style: 'width: 600px; height:1000px', scrolling: 'yes'}
    }

    var iframe = gapi.iframes.getContext().openChild(options);
  });
</script>

How can I make it works on an Angular 9 component, since <script> tags are not supported by the framework?

I already read many answers on how to dynamically load an external js using Injection, Renderer2 and other stuffs, but all examples only describe how to load the js library, not how to actually use it from the angular component.


Solution

  • You can declare a variable in your component *.ts file like following along your imports,

    declare const gapi: any;

    And in the function where you want to initiate the iframe load.

    gapi.load('gapi.iframes', function() {
       var options = {
         'url': 'https://play.google.com/work/embedded/search?token=web_token&mode=SELECT',
         'where': document.getElementById('container'),
         'attributes': { style: 'width: 600px; height:1000px', scrolling: 'yes'}
       }
    
       var iframe = gapi.iframes.getContext().openChild(options);
    });