Abbas
Abbas

Reputation: 3284

how to assign values to paper-items in a paper-dropdown-menu in polymer when using an array?

I want to assign values to the paper-items like below

<paper-item value="1">label1</paper-item>
 <paper-item value="2">label2</paper-item>
 <paper-item value="3">label3</paper-item>

but I am using an array to get my labels dynamically this way

 <paper-dropdown class="dropdown" on-core-overlay-open="{{comboDrop}}">
        <core-menu class="menu">
         <template repeat="{{processlist}}">
              <paper-item>{{}}</paper-item>
            </template>
        </core-menu>
    </paper-dropdown>

I assign an array to processlist later on when I get the required information. like

processlist=arr

, which allows me to display those labels in the paper-dropdown-menu.

How can i assign values to the paper-items and how can I access the values corresponding to each label ? I know that

detail.item.textContent

gets you the label, how can we get the values similarly

I'm fairly new to javascript and polymer components so any help in the right direction would be appreciated.

Thanks !

Upvotes: 2

Views: 4067

Answers (1)

flyandi
flyandi

Reputation: 1939

The repeat expression is an iterator and you can name the index and value:

<paper-dropdown class="dropdown" on-core-overlay-open="{{comboDrop}}">
 <core-menu class="menu">
  <template repeat="{{label, i in processlist}}">
   <paper-item value="{{i}}>{{label}}</paper-item>
  </template>
 </core-menu>
</paper-dropdown>

You can read more about expressions in Polymer here: https://www.polymer-project.org/docs/polymer/expressions.html

To answer your second part, I assume you want to retrieve the selected item's index of the dropdown? If that's the case you should use the paper-dropdown-menu component that allows you to specify the value attribute, in your case valueattr="value" and retrieve the current selected index via selected.Check out the examples here: https://github.com/Polymer/paper-dropdown-menu/blob/master/demo.html

Or if you just want to query the paper-items, you also can do this via the shadowRoot, e.g. in your main document:

// Get all paper-items
var items = document.querySelector("#dropdown").shadowRoot.querySelectors('paper-items[value]');

for(var i = 0; i < items.length; i++) {
 console.log("Value for item " + i + " = " + items[i].getAttribute("value"));
}

Or, if you want to implement a custom component with your very own click handler, then it's really simple:

On the actual item you just specify an on-click handler:

<paper-item value="{{i}}" on-click="{{handleClick}}">{{label}}</paper-item>

and then add the handler to your Polymer Component's code:

Polymer("my-component", {

 handleClick: function(e) {
   console.log("You clicked the item with value = " + e.target.getAttribute("value"));
 }
});

Hope that helps.

Upvotes: 2

Related Questions