DoK DoK - 1 month ago 10
Javascript Question

Change type of paper-input programmatically

Is there a way to toggle the type of a

paper-input
programmatically?
I have a
paper-input
element of type
password
and I want to change the type to
text
and vice versa.

This is the element what it looks like:

enter image description here

This is the implementation of the element:

<paper-input id="oldPassword"
type="password"
label="Old password"
no-label-float required>
<paper-icon-button suffix on-tap="toggleVisibility"
icon$="[[setVisibility(passVisible)]]">
</paper-icon-button>
</paper-input>


This is the JavaScript part:

toggleVisibility (e) {
this.passVisible = !this.passVisible;
e.currentTarget.type = this.passVisible ? 'text' : 'password';
}


The problem is that the type is set correctly but the
paper-input
element didn’t redraw itself.

Thanks for help!

Answer

The answer by Tony does a great job answering your question.

I'd like to add to it by introducing some more declarative bindings into your element.

See below how I toggle the input type and icon by observing the icon button's active property and using it with computed bindings.

Polymer({
  is: 'some-form',
  getPasswordType: function (passVisible) {
    return passVisible ? 'text' : 'password';
  },
  getVisibilityIcon: function(isVisible) {
    return isVisible ? 'visibility' : 'visibility-off';
  }
})
<base href="https://polygit.org/components/">

<link href="polymer/polymer.html" rel="import">
<link href="paper-input/paper-input.html" rel="import">
<link href="paper-icon-button/paper-icon-button.html" rel="import">
<link href="iron-icons/iron-icons.html" rel="import">

<some-form></some-form>

<dom-module id="some-form">
  <template>
    <paper-input id="oldPassword"
                 type="[[getPasswordType(passVisible)]]"
                 label="Old password"
                 value="secret"
                 no-label-float required>
        <paper-icon-button suffix toggles 
                           active="{{passVisible}}"
                           icon$="[[getVisibilityIcon(passVisible)]]">
      </paper-icon-button>
    </paper-input>
  </template>
</dom-module>