Search code examples
polymerpolymer-2.x

When upgrading to Polymer 2.0, what should I use to replace queryEffectiveChildren() in a Polymer.Element


I have a Polymer 1 element which uses queryEffectiveChildren() to check whether the slot's DOM is populated:

if(this.queryEffectiveChildren('[slot="description"]').childElementCount > 0) {

The queryEffectiveChildren function is not available in Polymer 2.0's Polymer.Element, so what should I use to perform the above check?


Solution

  • You could use the Polymer.LegacyElementMixin to use queryEffectiveChildren (or other legacy APIs):

    customElements.define('x-foo', class extends Polymer.LegacyElementMixin(Polymer.Element) {
      connectedCallback() {
        super.connectedCallback();
        let x = this.queryEffectiveChildren('[slot="description"]');
        // ...
      }
    });
    

    demo

    Or the equivalent, as described in the 2.0 upgrade guide:

    customElements.define('x-foo', class extends Polymer.LegacyElementMixin(Polymer.Element) {
      connectedCallback() {
        super.connectedCallback();
        let x = Polymer.FlattenedNodesObserver
                  .getFlattenedNodes(this)
                  .filter(n => n.nodeType === Node.ELEMENT_NODE)
                  .filter(n => n.parentNode.querySelector('[slot="description"]') === n);
                  // OR: .filter(n => n.getAttribute('slot') === 'description');
      }
    });
    

    demo