How to access the internals of a custom element defined via Polymer

I am creating a custom element in Polymer using Dart. I want to get some content from within a tag, for example:

<my-element>
  <name>doof</name>
</my-element>

      

Inside the dart code used to handle the elements of my element, I'm having a hard time getting the content of the "name" element. The code below shows some of my attempts:

@CustomTag('my-element')
    class MyElement extends PolymerElement {

     MyElement.created() : super.created() {

           // Will always find the first element in the document. That quickly
           // gets confusing when I have multiple instances of  <my-element> in the
           // document.
           final Element nameElement = querySelector("name");

           // Returns null
           final Element nameElement = shadowRoot.querySelector("name");
     }
}

      

... So I'm confused :-) Does anyone have any ideas?

+3


source to share


2 answers


First, leave the constructor created

separate, and maybe local variable initialization as well.
Override lifecycle callbacks like attached

or ready

. querySelector("name");

should work then. If you get the first element in the document, you should use this.querySelector("name");

(depends on your import) shadowRoot.querySelector("name");

for elements inside a tag of <template>

yours <my-element>

not for its children (like in your question).



@CustomTag('my-element')
    class MyElement extends PolymerElement {

     MyElement.created() : super.created();

     @override
     void ready() {

           // Will always find the first element in the document. That quickly
           // gets confusing when I have multiple instances of  <my-element> in the
           // document.
           final Element nameElement = this.querySelector("name");
     }
}

      

+1


source


this.shadowRoot.querySelector () scans the dom inside the current 'my-element' tag.

from



<my-element>
  <div id="myName">doof</div>
<my-element>

      

this.shadowRoot.querySelector ("# myName") will return DivElement

0


source







All Articles