Search code examples
drop-down-menupolymerweb-componentpaper-elements

Dynamically-generated paper-dropdown-menu initial selection issue


So I'm trying to dynamically generate a paper-dropdown-menu populated from an AJAX data source, which is working great using the code below:

<polymer-element name="my-element" attributes="selected">
  <template>

    <core-ajax auto url="/api/items/" response="{{items}}" handleAs="json"></core-ajax>
    <paper-dropdown-menu selected="{{selected}}">
      <template repeat="{{items}}">
        <paper-item name="{{id}}" label="{{name}}"></paper-item>
      </template>
    </paper-dropdown-menu>

  </template>

But if I set the initial selected item to be either the value of the published attribute, or a value that I set in the 'ready' callback, the dropdown menu item does not get selected when the items are loaded:

  <script>
  Polymer({
    publish: {
      selected: null
    }
  });
  </script>
</polymer-element>

I understand that this is happening because the 'selected' property is being set before the template in the dropdown gets bound, but my question is whether there is a way to either 1) defer the 'selected' property change until after the template is bound or 2) otherwise reliably set an initially selected value for the dropdown menu?


Solution

  • One option would be to not render the dropdown until the data is available.

    ex: http://jsbin.com/piyogo/13/edit

    <polymer-element name="foo-drop">
      <template>
        <core-ajax auto
                   url="http://www.json-generator.com/api/json/get/bJMeMASvTm?indent=2"
                   response="{{items}}"    
                   handleas="json">
        </core-ajax>
        <template if="{{items}}">
          <paper-dropdown-menu selected="{{selected}}">
            <template repeat="{{item in items}}">
              <paper-item label="{{item.name}}"></paper-item>
            </template>
          </paper-dropdown-menu>  
        </template>
      </template>  
      <script>
        Polymer({
          publish: {
            selected: null
          }
        });
      </script>
    </polymer-element>
    
    <foo-drop selected="2"></foo-drop>