Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom elements cannot access it's contents in the shadowRoot

I tried to access contents of my custom element in another custom elemnent shadow root.

index.html just has a my-tag-wrapper element:

<!-- import HTMLs and init Polymer-->
...
<my-tag-wrapper></my-tag-wrapper>
...

my_tag_wrapper.html contains a my-tag element with a paragraph element:

<polymer-element name="my-tag-wrapper" >
  <template>
    <my-tag>
      <p>wrapped my-tag contents</p>
    </my-tag>
  </template>
  <script type="application/dart" src="my_tag_wrapper.dart"></script>
</polymer-element>

my_tag.html just render it's contents:

<polymer-element name="my-tag" >
  <template>
    <content></content>
  </template>
  <script type="application/dart" src="my_tag.dart"></script>
</polymer-element>

my_tag.dart will print it's contents to console:

@CustomTag('my-tag')
class MyTagElement extends PolymerElement {
  ParagraphElement get p => this.querySelector('p');

  MyTagElement.created() : super.created() {
    var pe = p;
    var t = (pe == null) ? null : pe.text;
    print('my-tag p: ${t}');
    print('my-tag outerHtml: ${outerHtml}');
  }
}

However, my_tag.dart print:

my-tag p: null
my-tag outerHtml: <my-tag></my-tag>

Can I get my-tag contents in above codes?

Here is the example repo.

Edit:

I understood this problem with the clue provided by @Günter Zöchbauer's answer.

In the other shadowRoot, the contents of custom elements cannot be accessible on the created() constructor. The contents is accessible on and after attached().

I fixed my_tag.dart:

@CustomTag('my-tag')
class MyTagElement extends PolymerElement {
  ParagraphElement get p => this.querySelector('p');

  MyTagElement.created() : super.created() {
    _printContent(); // print null because contents is not rendered
  }

  @override
  attached() {
    super.attached();
    _printContent(); // print contents
  }

  _printContent() {
    var pe = p;
    var t = (pe == null) ? null : pe.text;
    print('my-tag p: ${t}');
    print('my-tag outerHtml: ${outerHtml}');
  }
}

I had a misunderstanding that a contents of a custom element is always accessible on created() constructor because the contents of my-tag is accessible on created() when it is a child in body element.

Edit: s/domReady/attached by the @Günter Zöchbauer's advice

like image 424
k-ui Avatar asked Nov 01 '22 20:11

k-ui


1 Answers

Because my-tag as a content node p becomes a child of my-tag-wrapper.shadowRoot.

You can access it using

(shadowRoot.querySelector('content') as ContentElement).getDistributedNodes()[0];
like image 88
Günter Zöchbauer Avatar answered Nov 15 '22 06:11

Günter Zöchbauer