Typel
Typel

Reputation: 1139

Add a Polymer paper-dropdown-menu to a page from javascript?

I'm trying to add a paper-dropdown-menu into my page from JavaScript. However, when I do it this way, it ends up malformed on the page - the list items display by default and do not collapse back into the list.

This is the basic structure of a paper-dropdown-menu, so it looks like I need to create 3 elements nested within each other and then append it to my target div...

<paper-dropdown-menu label="Type">
 <paper-menu class="dropdown-content">
  <paper-item>Test</paper-item>
 </paper-menu>
</paper-dropdown-menu>

To that end, I wrote this so far:

index.html

<paper-button id="AddList" on-tap="_addList">Add List</paper-button>
<div id="ListGoesHere"></div>

app.js

app._addList() = function(e) {
  // creating the dropdown container
  var elDropdown = document.createElement('paper-dropdown-menu');
  elDropdown.label = 'Type';

  // creating the paper-menu to go inside the paper-dropdown-menu
  var elMenu = document.createElement('paper-menu');
  elMenu.id = 'ProjectType';
  elMenu.className = 'dropdown-content';

  // creating one item (option)
  var elItem = document.createElement('paper-item');
  elItem.value = 'test';
  elItem.innerHTML = 'Test';

  // nesting the item inside of the menu
  elMenu.appendChild(elItem);

  // nesting the menu inside the dropdown
  elDropdown.appendChild(elMenu);

  // attaching the new dropdown element to the page/DOM
  document.querySelector('#ListGoesHere').appendChild(elDropdown);
};

It just doesn't seem to be nesting these elements properly - the paper-menu appears outside of the paper-dropdown-menu element and does not react at all when clicking the paper-dropdown-menu. I've done similar things with other Polymer elements such as paper-inputs and paper-textareas and they worked as expected. Is there something different/special about the dropdown elements?

Upvotes: 1

Views: 736

Answers (1)

Alon
Alon

Reputation: 2929

I think that this is not a good way to add elements to the polymer dom dynamically, this still does not render ok and the binding does not works.

The right way to implement this I think is to make list of dropDown menus and create dom-repeat template ,this is easier way.

<template is="dom-repeat" items="{{dropMenus}}">
   <paper-dropdown-menu label="Type">

       <paper-menu class="dropdown-content">
          <template is="dom-repeat" items="{{item}}">
            <paper-item>{{item}}</paper-item>
          </template>
        </paper-menu>

   </paper-dropdown-menu>
  </template>

And append to the itemsArray item by using the push method

  this.set('dropMenus',[['item1','item2'],['item1','item2'],['item1','item2']]);

or if you use app

  app.set('dropMenus',[['item1','item2'],['item1','item2'],['item1','item2']]);

Upvotes: 2

Related Questions