Skip to content

Instantly share code, notes, and snippets.

@cnative100
Last active March 9, 2017 15:44
Show Gist options
  • Save cnative100/dfe4fe10d9248d81eec8ab1a0903f16c to your computer and use it in GitHub Desktop.
Save cnative100/dfe4fe10d9248d81eec8ab1a0903f16c to your computer and use it in GitHub Desktop.
Processing Dynamically Created Input Elements in Polymer

It's common to have elements in a Polymer app that are dynamically rendered. Creating and processing these elements is fairly straightforward, but it's surprisingly difficult to find good information on doing it (at least as of this writing).

These code snippets show:

1.) How to create dynamic elements with a repeater template
2.) How to generate a unique id for each element
3.) How to access those elements in the Javascript with the query selector

<!-- This file is a snipped of a polymer element with an Array-type property
called category, the items within which have a unique identifier called 'id'.
Each item creates a paper-button, paper-icon, and iron-collapse element. The
button toggles the iron-collapse, and the item is simply attached to the button
for decoration. The icon changes depending on whether the iron-collapse is
toggled on or off.
Each element's id is bound to a function that creates a unique ID based on the
catalog ID. When the user clicks a button, the Javascript can grab the button's
id (which will have the form edit_<item.id> (e.g. edit_3) from the event
arguments. From there, we can use the ID and know prefixes of the other
elements to located them with the query selector. See the this.$$ calls in
toggleItemEdit().
-->
<template is="dom-repeat" items="{{categories}}">
<paper-button id="{{getCatalogEditButtonId(item.id)}}" style="float:right;" on-click="toggleItemEdit">
<iron-icon id={{getCatalogEditFormToggleIconId(item.id)}} icon="add"></iron-icon>
</paper-button>
<iron-collapse id="{{getCatalogCollapseId(item.id)}}">
<paper-card>
Rest assured that this is some amazing content right here.
</paper-card>
</iron-collapse>
</template>
<script>
properties: {
categories: {
type: Array
}
},
getCatalogEditButtonId: function(categoryId){
return "edit_" + categoryId;
},
getCatalogEditFormToggleIconId: function(categoryId){
return "editIcon_" + categoryId;
},
getCatalogCollapseId: function(categoryId) {
return "collapse_" + categoryId;
},
toggleItemEdit: function(e){
var formCollapseTarget = this.$$("#collapse_" + e.currentTarget.id.substring(5, 6));
var formCollapseIcon = this.$$("#editIcon_" + e.currentTarget.id.substring(5,6));
if(formCollapseIcon.icon == 'add'){
formCollapseIcon.icon = "close";
}
else{
formCollapseIcon.icon = "add";
}
formCollapseTarget.toggle();
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment