Search code examples
angularjspolymershadow-domtransclusion

Element transclusion


Is there something like angularjs directive's transclude attribute in polymer? Something what allows me to include some elements to a specific place in template?

I would like to achieve something like following:

<my-header title="My title">
    <my-header-item name="Item 1"></my-header-item>
    <my-header-item name="Item 2"></my-header-item>
</my-header>

which might be expressed:

<h1>My title</h1> <!-- "My title" given by my-header's title attribute -->
<ul>
    <li>Item 1 <!-- given by my-header-item -->
    <li>Item 2
</ul>

I am not sure if this is a task for polymer or if this is a typical way to use polymer. I am asking, because I started to like polymer and I would like to keep idiomatic thinking.


Solution

  • In Shadow DOM land, this is called distribution. To distribute light DOM nodes into the shadow dom, you use <content> insertion points.

    http://www.polymer-project.org/platform/shadow-dom.html#shadow-dom-subtrees

    It's quite literally a way to render nodes from light dom into placeholders in the shadow dom. If you want to do tricky things with the my-header/my-header-item title/name attributes, you can do something like this:

    <polymer-element name="my-header">
      <template>
        <ul>
          <template repeat="{{item in items}}">
            <li>{{item.name}}</li>
          </template>
        </ul>
        <content id="c" select="my-header-item"></content>
      </template>
      <script>
       Polymer('my-header', {
         domReady: function() {
           this.items = [].slice.call(this.$.c.getDistributedNodes());
         }
       });
      </script>
    </polymer-element>
    

    Demo: http://jsbin.com/hupuwoma/1/edit

    I have a more full-fledged tabs demo does this setup over on https://github.com/ebidel/polymer-experiments/blob/master/polymer-and-angular/together/elements/wc-tabs.html.