how to dynamically append an element to dom-if in Polymer?

孤人 提交于 2019-12-01 18:36:46

How about adding a span in your dom-if and appending it to that span?

Update after some comments : We need to use this.async for the item to be found. Using the ready-event only works when the condition is true initially. So you could append the element in a conditionChanged-observer - this is a working example :

<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>

Try it here : http://plnkr.co/edit/1IIeM3gSjHIIZ5xpZKa1?p=preview .

A side-effect of using dom-if in this case is that after setting the condition to false, the element disappears completely and gets added on the next condition-change again. So every change before setting the condition to false gets lost. You could work around it by putting the added element somewhere hidden when the condition changes and getting it back later, but I don't think this is a good idea, if the following is an alternative :

The Polymer-team recommends using dom-if only if there is no other way, like hiding the element. So, if it is possible you also could do something like this (condition has to be true to hide the element) :

<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>

Try it here : http://plnkr.co/edit/mCtwqmqtCPaLOUveOqWS?p=preview

The template element itself will not be added to the DOM, this is the reason you can't access it using querySelector or getElementXxx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!