Question

I have a Polymer element called edit-box that acts as a container for a set of unspecified elements based on incoming data.

<link rel="import" href="/assets/bower_components/polymer/polymer.html">
<link rel="import" href="/assets/elements/field-text.html">
<link rel="import" href="/assets/elements/field-hidden.html">

<polymer-element name="edit-box" attributes="dataFields">
    <template>
        <template repeat="{{dataField in dataFields}}">
            <field-{{dataField.Type}}></field-{{dataField.Type}}>
        </template>
        <input type="button" value="Save" />
    </template>
    <script>
        Polymer('edit-box', {
            ...
        }
    </script>
</polymer-element>

dataField.Type might be "text" or "hidden", etc.

I have created other polymer elements called field-text and field-hidden, etc.

This is just the basic idea, I know it's not polished. How can I go about looping through my dataFields and render different elements within this edit-box container element based on what exists inside of that data set?

Était-ce utile?

La solution

It would be super cool to bind to an element name like this, but it's not possible. Polymer's internal Node.bind() library needs a property, TextNode, etc. to bind to. In the case of <field-{{dataField.type}}>, the {{}} is meaningless, as there's nothing to latch on to.

One way you can achieve what you want is to use conditional templates:

<template repeat="{{dataField in dataFields}}">
  <template if="{{dataField.type == 'text'}}">
    <field-text></field-text>
  </template>
  <template if="{{dataField.type == 'chart'}}">
    <field-chart></field-chart>
  </template>
</template>

http://jsbin.com/yuqinoxa/1/edit

Even better would be to create a generic element, and give it a type attribute to bind to:

<template repeat="{{dataField in dataFields}}">
  <field-element type="{{dataField.type}}"></field-element>
</template>

http://jsbin.com/tirokuso/1/edit

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top