Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dom-repeat template fails to render array with error 'expected array for items'

I have a simple template that renders an array object. However, it fails with the following message:

[dom-repeat::dom-repeat]: expected array for `items`, found [{"code":1,"name":"Item #1"},{"code":2,"name":"Item #2"},{"code":3,"name":"Item #3"}]

The array is passed in the attribute of the custom element in the following format:

[{"code":1,"name":"Item #1"},{"code":2,"name":"Item #2"},{"code":3,"name":"Item #3"}]

I have read the docs on template repeaters several times and still unable to find what I am doing wrong.

Any help would be much appreciated!

Here is my custom element:

<dom-module id="x-myelement">   
    <template>
        <div>
            <h1>{{title}}</h1>
            <ul>
                <template is="dom-repeat" as="menuitem" items="{{items}}">
                    <li><span>{{menuitem.code}}</span></li>
                </template>
            </ul>           
        </div>
    </template>
    <script>
        (function() {
            Polymer({
              is: 'x-myelement',

              title: String,

              items: {
                  type: Array,
                  notify: true,
                  value: function(){ return []; }
              }           
            });
          })();
    </script>
</dom-module>

And here is now I use it:

<x-myelement title="Hello Polymer" 
             items='[{"code":1,"name":"Item #1"},{"code":2,"name":"Item #2"},{"code":3,"name":"Item #3"}]'>
</x-myelement>
like image 928
Chakkaradeep Chandran - MSFT Avatar asked Sep 27 '22 02:09

Chakkaradeep Chandran - MSFT


1 Answers

You need to put your element properties into the properties object (see the Polymer documentation on properties):

Polymer({
  is: 'x-myelement',
  properties: {
    title: String,
    items: {
      type: Array,
      notify: true,
      value: function() {return [];}
    }
  }
});

Otherwise Polymer has no information about your properties. It treated items as a string and didn't parse the attribute value as a JSON array. Eventually dom-repeat was passed a string for its items property as well, resulting in the error that you saw.

like image 185
Dirk Grappendorf Avatar answered Oct 09 '22 19:10

Dirk Grappendorf