Query elements inside <content> of a custom element

时间秒杀一切 提交于 2019-12-29 07:16:11

问题


I have two custom elements. The one of them is nested to another one. Something like this:

<polymer-element name="my-element">
  <template>
  <div>
    Bla, Bla, Bla!
  </div>
  </template>
  <script type="application/dart" src="my_element.dart"></script>
</polymer-element>

<polymer-element name="my-decorator">
  <template>
  <div>
    <div>Decorator</div>
    <content>
      <!-- my-element will be here-->
    </content>
  </div>
  </template>
  <script type="application/dart" src="my_decorator.dart"></script>
</polymer-element>

using both custom elements in index.html:

<my-decorator>
  <my-element></my-element>
</my-decorator>

How can I query the instance of the second element from the code behind of the first one?

@CustomTag('my-decorator')
class MyDecorator extends PolymerElement {
  bool get applyAuthorStyles => true;

  MyDecorator.created() : super.created() {

    // TODO:
    // get my-element instance here!
    // ..

  }
}

回答1:


@override
void attached() { 
  // attached is an example the code an be placed somewhere else
  // but some places are executed before the childs are added 

  super.attached();

  var nodes = (shadowRoot.querySelector('content') as ContentElement).getDistributedNodes();

  var myElement = nodes.firstWhere((e) => e is MyDecorator); // not sure about this `e is MyDecorator`
  // you have to choose some way to identify the node in the result
  // I currently have no example where I can try it myself
}

if the tag has an id attribute like id='c1' then this works too

  var nodes = ($['c1'] as ContentElement).getDistributedNodes();


来源:https://stackoverflow.com/questions/22071232/query-elements-inside-content-of-a-custom-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!