![](/img/trans.png)
[英]How to trigger observer on child element when nested in dom-if Polymer
[英]how to dynamically append an element to dom-if in Polymer?
我的目标是动态地将元素附加到现有的dom-if
。 问题是,在追加之后我可以在DOM中看到附加元素三但它从不会在condition
做出反应并始终隐藏。
<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-if
和input
探索DOM表明<input />
元素实际上不是dom-if
的子元素,但它就在它旁边。
<template>
<template is="dom-if" if="[[condition]]" restamp>
<input />
</template>
</template>
这给了我一个线索,我可能应该将我的元素追加到dom-if
...但是现在最大的问题是如何对dom-if
如果condition
满足则应该渲染附加元素。 有任何想法吗?
如何在dom-if中添加跨度并将其附加到该跨度?
一些评论后更新:我们需要使用this.async来找到项目。 使用ready-event仅在条件为true时才有效。 所以你可以在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-team建议使用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
模板元素本身不会添加到DOM中,这就是您无法使用querySelector
或getElementXxx
访问它的原因
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.