我的目标是将一个元素附加到现有 dom-if
动态。问题是,附加后我可以在 DOM 3 中看到附加元素,但它永远不会对 condition
使用react。并始终隐藏。
<template>
<template id="domif" is="dom-if" if="[[condition]]" restamp></template>
</template>
ready() {
var el = document.createElement("input");
Polymer.dom(this.$.domif).appendChild(el);
Polymer.dom.flush();
}
使用硬编码探索 DOM
dom-if
和 input
显示 <input />
element 实际上不是 dom-if
的子元素但是就住在旁边。。<template>
<template is="dom-if" if="[[condition]]" restamp>
<input />
</template>
</template>
这给了我一个线索,我可能应该将我的元素附加到
dom-if
旁边。 ... 但现在最大的问题是如何对dom-if
说如果 condition
,则应呈现该附加元素很满意。有任何想法吗?
最佳答案
在 dom-if 中添加一个跨度并将其附加到该跨度如何?
一些评论后更新:我们需要使用 this.async 才能找到该项目。仅当条件最初为真时才使用就绪事件。所以你可以在 conditionChanged-observer 中附加元素 - 这是一个工作示例:
<dom-module id='my-element1'>
<template>
<template is="dom-if" if="[[condition]]" restamp>
<span id="appendHere"></span>
</template>
</template>
</dom-module>
<script>
Polymer({
is: 'my-element1',
properties: {
condition: {
type: Boolean,
observer: "_conditionChanged"
}
},
_conditionChanged: function(newVal) {
if (newVal) {
this.async(function() {
var el = document.createElement("input");
Polymer.dom(this.$$("#appendHere")).appendChild(el);
Polymer.dom.flush();
});
}
}
});
</script>
在这里试试:http://plnkr.co/edit/1IIeM3gSjHIIZ5xpZKa1?p=preview .
在这种情况下使用 dom-if 的副作用是,在将条件设置为 false 后,元素完全消失并在下一次条件更改时再次添加。因此,在将条件设置为 false 之前的所有更改都会丢失。您可以通过在条件发生变化时将添加的元素隐藏在某个地方并稍后将其恢复来解决它,但我认为这不是一个好主意,如果以下是替代方案:
Polymer 团队建议使用 dom-if,除非没有其他方法,例如隐藏元素。因此,如果有可能,您也可以执行以下操作(条件必须为真才能隐藏元素):
<dom-module id='my-element1'>
<template>
<span id="appendHere" hidden$="[[condition]]"></span>
</template>
</dom-module>
<script>
Polymer({
is: 'my-element1',
properties: {
condition: Boolean
},
ready: function() {
var el = document.createElement("input");
Polymer.dom(this.$.appendHere).appendChild(el);
Polymer.dom.flush();
}
});
</script>
在这里试试:
http://plnkr.co/edit/mCtwqmqtCPaLOUveOqWS?p=preview
关于polymer - 如何在Polymer中将元素动态附加到dom-if?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34137859/