Polymer: how to dynamically import an item

Can someone tell me how I can import an element depending on the value of the Polymer attribute? I thought I could use data binding, but ... It does not work. Is it possible to import an item dynamically?

Code example

here:

<link rel="import" href="app-window/{{name}}-app.html"> 
//This was my first idea (obviously doesn't work)


<polymer-element name="window-base" attributes="name" >
    <template>
        <link rel="stylesheet" href="window-base.css">
        <section id="app">
            <!--here will go the instance-->
        </section>
    </template>
    <script>
        Polymer('window-base', {
            name: "Finder",
            ready: function () {
                this.instanceApp();
            },
            instanceApp: function () {
            //this depends on the import made
                var app=document.createElement(this.name + "-app");
                this.$.app.appendChild(app);    
            }
        });
    </script>
</polymer-element>

Thank!

+4
source share
4 answers

According to Polymer 1.0 Migration Guide:

The global function Polymer.import is replaced by importHref. The new method can be called from the as this.importHref element. Outside the element, it can be called as Polymer.Base.importHref.

So...

this.importHref(["yourComponent.html"], function() {})
+9
source

, . , . Polymer.import:

0,5

Polymer.import( ['/elements/'+this.module+'-module.html'], function() {
    console.log('/elements/'+this.module+'-module.html loaded');
    this.onComplete();
}.bind(this));

Update Polymer 1.0

link [rel= "import" ]

var link = document.createElement('link');
link.setAttribute('rel', 'import');
link.setAttribute('href', 'elements/app-module.html');
document.body.appendChild(link)
+6

How about something like that? I have not tested some of them (the WebComponentsReady event can only be fired in a window), but if you can post jsbin or codepin that will help:

Polymer('window-base', {
  name: 'Finder',
  domReady: function() {
    this.nameChanged();
  },
  nameChanged: function() {
    var importElem = document.createElement('link');
    importElem.rel = 'import';
    importElem.href = 'app-window/' + name + '-app.html';
    importElem.addEventListener('WebComponentsReady', function() {
      var app = document.createElement(this.name + "-app");
      this.$.app.appendChild(app);
    }.bind(this));
    this.appendChild(importElem);
  }
});
0
source

The decision made also works for Polymer 2

Link to Polymer 2 importHref docs

Polymer.importHref([`bower_components/${plugin}/${plugin}.html`], () => {
    //on load
}
0
source

Source: https://habr.com/ru/post/1540580/


All Articles