在聚合物元素中动态创建html导入
有谁知道如何动态地将html导入添加到聚合物元素(版本1.0)?
以下代码似乎无法正常工作并抱怨......
HTML element <link> is ignored in shadow tree.
有没有人知道这方面或知道更好的方法?
<!-- 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>
答案 0 :(得分:11)
Polymer 1.0在每个Polymer组件上都有效用函数importHref(href, onLoad, onError)
。要动态导入和添加外部元素,您可以使用以下代码:
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
});
答案 1 :(得分:1)
我不确定您是否可以动态添加HTML导入并使其在另一个元素内部工作,但您需要使用Polymer的DOM API。请参阅here。
这样的事情:
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);
}
});