我正在尝试在运行时创建一个ParagraphElement,并在聚合物组件中创建Div元素,如下所示:
<polymer-element name="my-element" extends="div">
<template>
<p>
<button on-click="updateMessage" data-msg="You clicked Show">Show Message</button>
<button on-click="updateMessage" data-msg="You clicked Hide">Hide Message</button>
<button on-click="addPelement" >Add P element</button>
</p>
<p id="message">{{ message }}</p> <!-- bind the message -->
<div id="mydiv"></div>
</template>
<script type="application/dart" src="my_element.dart"></script>
</polymer-element>
和dart文件如下:
@CustomTag('my-element')
class MyElement extends PolymerElement with ObservableMixin {
@observable var message;
void updateMessage(Event e, var detail, Element target) {
message = target.attributes['data-msg']; // extract the data- attribute
}
void addPelement(Event e) {
var item = new ParagraphElement ();
item.text="new p element";
DivElement d = query("#mydiv");
d.children.add(item);
}
}
行查询(“#mydiv”)返回null元素。
答案 0 :(得分:2)
您需要使用以下代码访问div元素:
DivElement d = $['mydiv'];
答案 1 :(得分:0)
需要向ShadowRoot添加新元素
DivElement d = this.shadowRoot.query("#mydiv");