Search code examples
javascripthtmlpolymerweb-component

Why doesn't Polymer insert the content?


I'm trying to understand the Web Components, so I want to create a web component that would "wrap" a select tag into the select2.

Here's my main HTML:

<html>
  <head>
    <title>Web components</title>
    <meta charset="utf-8"></meta>
    <script src="bower_components/webcomponentsjs/webcomponents.min.js"></script>
    <link rel="import" href="elements/select2-select.html"></link>
  </head>
  <body>
    <div>
      <select2-select>
        <option value="A">A</option>
        <option value="B">B</option>
        <option value="C">C</option>
      </select2-select>
    </div>
  </body>
</html>

And my custom element:

<link rel="import" href="../bower_components/polymer/polymer.html"></link>

<polymer-element name="select2-select">
  <template>
    <select id="main">
      <content></content>
    </select>
  </template>
  <script>Polymer({});</script>
</polymer-element>

The problem is, the option tags aren't being inserted in the shadow DOM:

dom-example

What am I doing wrong? I'm running Firefox on Ubuntu 14.04.2, if it's anyhow relevant.

Thank you very much.


Solution

  • Yeah that happens, the easiest way around it is to use attributes. I've amended your original script to make it work.

    Main html:

    <html>
      <head>
        <title>Web components</title>
        <meta charset="utf-8"></meta>
        <script src="bower_components/webcomponentsjs/webcomponents.min.js"></script>
        <link rel="import" href="elements/select2-select.html"></link>
      </head>
      <body>
        <div>
          <select2-select options='[
          {"value":"1","text":"1"},
          {"value":"2","text":"2"},
          {"value":"3","text":"3"},
          {"value":"4","text":"4"}
          ]'></select2-select>
        </div>
      </body>
    </html>
    

    custom element:

    <link rel="import" href="../bower_components/polymer/polymer.html">
    <polymer-element name="select2-select" attributes="options">
      <template>
        <select id="main">
            <template repeat="{{option in options}}">
            <option value={{option.value}}>{{option.text}}</option>
            </template>
        </select>
      </template>
      <script>
        Polymer('select2-select', {
            publish: {
                options: {},
            }
        });
      </script>
    </polymer-element>