polymerpolymer-2.xdom-repeat

How to Pass in Dropdown Value to dom-repeat


I am trying to pass in a value to a dom-repeat template, but the behavior defaults to the first item in the array. I am trying to set a string from an array of strings.

Parent Component

<select value="[[entry.method]]"
  on-change="_changeMethod">
  <template is="dom-repeat" items="[[entry.methods]]">
    <option value="[[item]]">[[item]]</option>
  </template>
</select>

Child Component

this.dispatchEvent(new CustomEvent('add-item', {
  bubbles: true,
  composed: true,
  detail: {
    method: 'b',
    methods: ['a', 'b', 'c']
  }));

The drop down defaults to 'a'

How can I pass in 'b' to set the initial drop down value?


Solution

  • Assuming method is the desired selection from methods, you could modify your event handler for the add-item event to select the corresponding index. The trick is to wait for the next render frame (using Polymer.RenderStatus.afterNextRender()), at which point the DOM has updated with the new entry.

    addItem(e) {
      const entry = e.detail;
      const selectedIndex = entry.methods.indexOf(entry.method);
      this.entry = entry;
    
      Polymer.RenderStatus.afterNextRender(this, () => {
        this.$.mySelect.selectedIndex = selectedIndex;
      });
    }
    

    demo