Search code examples
javascriptpolymerweb-componentselectors-api

Polymer querySelector can't find custom polymer element in polymer element


I am trying to get a custom Polymer element defined in another element via querySelector or equivalent. Code I have is as follows:

<polymer-element name="component-elem">
<!-- custom elem here -->
<ajax-service id="testComp"></ajax-service>
<template>

</template>
<script>
Polymer({
ready: function(){
    var x = this.shadowRoot.querySelector('#testComp');
    console.log(x); //always prints null

}
});
</script>

</polymer-element>

I've seen numerous stack overflow posts similar to what I am trying to accomplish, but have not had any good results, I've also tried:

this.$.testComp

and

this.shadowRoot.querySelectorAll('#testComp')

which does return an object but I am unclear as to how to use the result.

My end goal is to add a custom event listener that listens for an event fired from the <ajax-service> element.

I am hoping to process results from the Ajax-service element into repeating elements by use of template repeat={{response}}. I do not want the Ajax-service element duplicated, therefore Ajax-service is outside of template.

Can anyone give any advice?


Solution

  • <polymer-element name="component-elem">
    <!-- custom elem here -->
    <template>
      <ajax-service id="testComp"></ajax-service>
    
      <template repeat="{{response}}">
        // html for looped items
        <template if="{{response.data}}">
          // do something with response.data
        </template>
      </template>
    </template>
    <script>
      Polymer({
        ready: function(){
          var x = this.shadowRoot.querySelector('#testComp');
          console.log(x); //always prints null
    
         }
      });
    </script>
    
    </polymer-element>
    

    the issue is cause you do not have the ajax element inside your element's template. the first template in the custom element is where the shadowdom starts. so for any item to be selected with those selectors it must be in the first template in the element. using a repeating template later inside the elements original template.

    keep in mind templates can be nested like in the example above.