How to insert a template using a data-binding slot in Polymer2

I would like to add a rendering template from the parent component to the child component using the <slot>insertion points . The entered template contains data binding to the property of the child component ( my-child.datain this case).

<dom-module id="my-parent">
  <template>
    <my-child>
      <template>
        <div>Child data property: [[data]]</div>
      </template>
    </my-child>
  </template>
  ...

The child component of the rendering basically looks like this:

<dom-module id="my-child">
  <template>
    <header></header>
    <slot></slot>
    <footer></footer>
  </template>

  <script>
    class MyChild extends Polymer.Element {
      static get is() { return 'my-child'; }
      static get properties() {
        return {
          data: { ... }
        };
      }
      ...

I'm not sure if this is possible at all with Polymer2. To achieve this, Vue2 has the concept of a "scoped slot" . Thank you in advance for any feedback!

+4
source share
1 answer

. , <template> .

HTML - DOM <template>, <template> . <slot>, - DOM my-child.

, : http://jsbin.com/loqecucaga/1/edit?html,console,output

data input, , .

connectedCallback:

var template = this.querySelector('template');
this.__instance = this._stampTemplate(template);
this.$.content.appendChild(this.__instance);

- div, - my-child:

<div id="content"></div>

, :

<link href="polymer/polymer-element.html" rel="import"/>
<link href="polymer/lib/mixins/template-stamp.html" rel="import"/>

<dom-module id="my-parent">
  <template>
    <my-child>
      <template>
        <div>Child data property: [[data]]</div>
      </template>
    </my-child>
  </template>

  <script>
    class MyParent extends Polymer.Element {
      static get is() { return 'my-parent'; }
    }

    window.customElements.define(MyParent.is, MyParent);
  </script>
</dom-module>

<dom-module id="my-child">
  <template>
    <header>Header</header>
    <div id="content"></div>
    <footer>Footer</footer>
    <input type="text" value="{{data::input}}" />
  </template>

  <script>
    class MyChild extends Polymer.TemplateStamp(Polymer.Element) {
      static get is() { return 'my-child'; }
      static get properties() {
        return {
          data: {
            type: String,
            value: 'Hello, World!'
          },
        };
      }

      connectedCallback() {
        super.connectedCallback();

        var template = this.querySelector('template');
        this.__instance = this._stampTemplate(template);
        this.$.content.appendChild(this.__instance);
      }
    }

    window.customElements.define(MyChild.is, MyChild);
  </script>
</dom-module>

<my-parent></my-parent>
+7

Source: https://habr.com/ru/post/1678697/


All Articles