Search code examples
google-visualizationpolymergoogle-web-component

<google-chart> does not work inside <template is="dom-bind">


<google-chart> element is not working for me (does not display anything) when inside <template> (<template is="dom-bind"> on the main document or in other element's <template>). On the other hand it works when I put it outside <template is="dom-bind"> on the main document.

https://jsbin.com/fivamu/edit?html,output

<!DOCTYPE html>
<html>

<head>
  <base href="https://polygit.org">
  <script src="/components/webcomponentsjs/webcomponents-lite.min.js"></script>
  <link rel="import" href="/components/polymer/polymer.html">
  <link rel="import" href="/components/google-web-components/google-web-components.html">
</head>

<body>
  <template is="dom-bind">
    <h2>Doesn't work here:</h2>
    <google-chart type='geo' data='[["Country", "Popularity"],["Germany", 200],["United States", 300],["Brazil", 400],["Canada", 500],["France", 600],["RU", 700]]'></google-chart>
  </template>
  <h2>Works here:</h2> 
  <google-chart type='geo' data='[["Country", "Popularity"],["Germany", 200],["United States", 300],["Brazil", 400],["Canada", 500],["France", 600],["RU", 700]]'></google-chart>
</body>

</html>


Solution

  • This will work (tested in your jsbin):

    <!DOCTYPE html>
    <html>
    <head>
      <base href="https://polygit.org">
      <script src="/components/webcomponentsjs/webcomponents-lite.min.js"></script>
      <link rel="import" href="/components/polymer/polymer.html">
      <link rel="import" href="/components/google-web-components/google-web-components.html">
    </head>
    <body>      
      <template id="t" is="dom-bind">
        <h2>Doesn't work here:</h2>
        <google-chart id='map'></google-chart>
      </template>
      <h2>Works here:</h2>    
      <google-chart type='geo' data='[["Country", "Popularity"],["Germany", 200],["United States", 300],["Brazil", 400],["Canada", 500],["France", 600],["RU", 700]]'></google-chart>
    </body>
    
    
    <script>
      var t = document.querySelector('#t');  
    
      // The dom-change event signifies when the template has stamped its DOM.
      t.addEventListener('dom-change', function() {
        // auto-binding template is ready.
        console.log('ready');
        var map = document.querySelector('#map');
        map.setAttribute('type', 'geo');
        map.setAttribute('data', '[["Country", "Popularity"],["Germany", 200],["United States", 300],["Brazil", 400],["Canada", 500],["France", 600],["RU", 700]]');
      });
    </script>
    </html>
    

    The google-chart element relies on async calls to Google APIs. If these calls do not resolve before the template has stamped its DOM, the google-chart is incomplete. Adding the data field after the auto-binding template is ready will simulate the behaviour outside of a template.