Search code examples
polymerpolymer-1.0polymer-2.x

getContentChildren equivalent in Polymer 2


I have a custom element

<!-- element template -->
<dom-module id="custom-element">
  <template>
    <style></style>
    <div class="toggle">
      <slot id="toggleContent" name="toggle"></slot>
    </div>
  </template>
  <script>...</script>
</dom-module>

<!--usage-->
<custom-element>
  <div slot="toggle">I'm the toggle</div>
</custom-element>

In Polymer 1.0, I could get the distributed child node by using

[this.getContentChildren('#toggleContent')\[0\];][1] 

which would return <div toggle>I'm the toggle</div>

However in Polymer 2. getContentChildren isn't supported anymore and doing it this way

this.$.toggleContent.assignedNodes({flatten: true}).filter(function(n) {
  return (n.nodeType === Node.ELEMENT_NODE);
});

doesn't return me the expected element, <div slot="toggle">I'm the toggle</div>.

How do I get the equivalent result using assignedNodes() in Polymer 2?

Please see following plunker Thanks.


Solution

  • Use the following code:

    this.shadowRoot
      .querySelector('#toggleContent')
      .assignedNodes({flatten:true})
      .filter(n => n.nodeType === Node.ELEMENT_NODE)
    

    But if you have single slot then you can just do:

    this.shadowRoot
          .querySelector('slot')
          .assignedNodes({flatten:true})
          .filter(n => n.nodeType === Node.ELEMENT_NODE)
    

    The this.$ hash is created when the shadow DOM is initialized. Nodes created dynamically are not added to the this.$ hash. So, you have to use this.shadowRoot.querySelector.

    Update After the demo provided:

    _toggleEl is an array/object and you are comparing it with an element. So, it is returning false always. So, use var equal = elementClicked === this.toggleEl[0] like you did in polymer 1.