Dynamically created html import inside a polymer e

2019-04-11 12:14发布

Dynamically created html import inside a polymer element

Does anyone know how to dynamically add a html import into a polymer element (version 1.0)?

The code below doesn't seem to work and complains that the.. HTML element <link> is ignored in shadow tree.

Does anyone know any way around this or know a better way?

<!-- here is where the created import could go -->

<dom-module id="my-component">

<!-- here is where I'd ideally like the import to be created -->

  <template>
    <div id="container">

      <!--This is where my dynamically loaded element should be placed-->

    </div>
  </template>

  <script>
    Polymer({is:'my-component',
      attached: function(){

        var importElem = document.createElement('link');
        importElem.rel = 'import';
        importElem.href = '/components/my-dynamic-sub-component.html';
        this.root.appendChild(importElem);
        var app = document.createElement('my-dynamic-sub-component');
        this.$.container.appendChild(app);

      }
    });
  </script>

</dom-module>

2条回答
走好不送
2楼-- · 2019-04-11 12:43

I am not sure if you can dynamically add an HTML import and get it to work inside another element but you need to use Polymer's DOM API. See here.

Something like this:

Polymer({is:'my-component',
  attached: function(){

    //create element and add it to this 
    var importElem = document.createElement('link');
    importElem.rel = 'import';
    importElem.href = '/components/my-dynamic-sub-component.html';
    Polymer.dom(this.root).appendChild(importElem);
    var app = document.createElement('component-controler');
    Polymer.dom(this.$.container).appendChild(app);
  }
});
查看更多
三岁会撩人
3楼-- · 2019-04-11 12:45

Polymer 1.0 has the utility function importHref(href, onLoad, onError) on every Polymer component. To dynamically import and add your external element you could use this code:

this.importHref('path/to/page.html', function(e) {
  // e.target.import is the import document.
  var newElement = document.createElement('new-element');
  newElement.myProperty = 'foo';

  Polymer.dom(this.$.container).appendChild(newElement);  
}, function(e) {
  // loading error
});
查看更多
登录 后发表回答