0

In Polymer 0.5, you could do:

<template bind ref="howdyTpl"></template>
...
<template id="howdyTpl">Howdy {{whatever}}</template>

And the template with id 'howdyTpl' would get stamped where referenced in the ref attribute.

How can I do something similar in Polymer 1.0?

Trevor Dixon
  • 23,216
  • 12
  • 72
  • 109

2 Answers2

1

Here's a custom element that does something similar.

Polymer({
  is: 'bind-ref',

  properties: {
    ref: {
      type: String,
      observer: 'refChanged',
    },
  },

  refChanged: function(newRef, oldRef) {
    if (oldRef != undefined) {
      this._removeChildren();
      this._stamp();
    }
  },

  _stamp: function() {
    this._parent = Polymer.dom(this).parentNode;
    var rootEl = this._parent;
    while (Polymer.dom(rootEl).parentNode) {
      rootEl = Polymer.dom(rootEl).parentNode;
    }

    var tpl = Polymer.dom(rootEl).querySelector('#' + this.ref);
    var tplRoot = tpl.stamp().root;
    this._children = Array.prototype.slice.call(tplRoot.childNodes);
    Polymer.dom(this._parent).insertBefore(tplRoot, this);
  },

  _removeChildren: function() {
    for (var i = 0; i < this._children.length; i++) {
      Polymer.dom(this._parent).removeChild(this._children[i]);
    }
  },

  attached: function() { this._stamp(); },
  detached: function() { this._removeChildren(); },
});

The target template element must be a dom-template element.

<bind-ref ref="howdyTpl"></bind-ref>
<template is="dom-template" id="howdyTpl">Howdy <span>{{whatever}}</span></template>

(Code snippets licensed Apache 2.0.)

Trevor Dixon
  • 23,216
  • 12
  • 72
  • 109
  • Sadly, but this works when both bind-ref and template are siblings only. Does not work if bind-ref is inside a – miyconst Jun 02 '15 at 15:25
  • @miyconst It's working OK for me inside `dom-repeat`. What issue are you seeing? Also, I just fixed it so it removes the stamped elements when detached. – Trevor Dixon Jun 02 '15 at 19:03
  • I am trying to make a custom data-grid component. User should be able to define a custom template for a column. Draft work is available here: http://miyconst.github.io/ct-data-grid/ The Actions column has a template using bind-ref, but the binding does not work inside. – miyconst Jun 04 '15 at 10:10
1

I've created an element that resolves this problem. It's kind of a hack, but it works... including with multi-depth file inclusion and data binding that the other answer provided did not handle.

Brandon
  • 570
  • 2
  • 9