![](/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.