2

From this answer https://stackoverflow.com/a/26891895/2117440, I know that is possible to bind a referenced template. However when I do this:

<polymer-element name="data-ul" extends="ul" attributes="items">
  <!-- this is the replacement of content tag -->
  <template repeat="{{item in items}}">
    <template bind="{{item}}" ref="itemTemplate"></template>   
    <input type="button" value="Add Item" on-click="{{addItem}}"/>
  </template>
  <script type="application/dart" src="data-ul.dart"></script>
</polymer-element>

and the respective dart class:

@CustomTag('data-ul')
class DataUl extends LiElement with Polymer, Observable {
  DataUl.created() : super.created();

  @published List items;

  void parseDeclaration(Element elementElement) {
    var t = this.querySelector('#itemTemplate'); // Gets the template with id itemTemplate from the content html
    if(t != null)  // if not null
      elementElement.append(t); // append itemTemplate to elementElement

    super.parseDeclaration(elementElement); // call super
  }

  void addItem(Event e) {
    var item = nodeBind(e.target).templateInstance.model['item'];
    items.add(item);
  }
}

the items get added to the model correctly, but the itemTemplate is not rendered again. I think this is because the itemTemplate is removed from the scope, so it cannot be accessible again for rendering.

Should I use other method instead parseDeclaration?

Should I insert the itemTemplate in other place?

Community
  • 1
  • 1
Luis Vargas
  • 2,466
  • 2
  • 15
  • 32

1 Answers1

0

Instead of using elementElement, we should use element.templateContent:

@CustomTag('data-ul')
class DataUl extends LiElement with Polymer, Observable {
  DataUl.created() : super.created();

  @published List items;

  void parseDeclaration(Element elementElement) {
    // We need to remove previous template from element.templateContent
    // in that way it no continues adding a new content every time that we instantiate 
    // this component.
    var previousTemplate = element.templateContent.querySelector('#itemTemplate');
    if(previousTemplate != null)
      previousTemplate.remove();

    var t = this.querySelector('#itemTemplate'); // Gets the template with id itemTemplate from the content html
    if(t != null)  // if not null
      element.templateContent.append(t); // append itemTemplate to element.templateContent
    else
      element.templateContent.append(new TemplateElement()..id='itemTemplate');  //if no template is added append an empty template to avoid errors

    super.parseDeclaration(elementElement); // call super
  }

  void addItem(Event e) {
    var item = nodeBind(e.target).templateInstance.model['item'];
    items.add(item);
  }
}
Luis Vargas
  • 2,466
  • 2
  • 15
  • 32