Search code examples
javascriptpolymerpolymer-2.x

Paper-input value not accessible Polymer


I am pretty new with Polymer but think it is a great concept, although I have some troubles achieving pretty basic stuff that I normally have no problem with.

I have a template where I have a paper-input element. If I fill this element, I want to be able to click a button and transfer the value from that input field to somewhere else. Simple right?

Nope, no matter what I do, I can't seem to access the value of that input field. It's like the ID doesn't exist. I think it is because of the shadow dom, but I have no clue at all why!

I have tried with this.$.messaged.value, document.querySelector('#messaged').value and more without success. What else is there to do? Thanks in advance!!

<link rel="import" href="../../../bower_components/paper-input/paper-input.html">
<dom-module id="dd-bully">
    <template>
 <paper-input id="messaged" value="{{messaged}}"></paper-input>
    <paper-button raised on-tap="sendmsg"></paper-button>
    </template>
    <script src="bully.js"></script>
</dom-module>

And the script content below:

class Bully extends Polymer.Element {
        static get is() {
            return 'dd-bully';
        }

        static get properties() {
            return {
                messaged: {
                    type: String,
                    value: "test message"
                }
            };
        }
        sendmsg() {
            this.messaged = window.msg /* latest test */
            console.log(messaged)
            window.socket.emit('sendmsg', window.msg, err => {
                if (err) {
                    console.error(err);
                    return;
                }
            });
        }
    }
    customElements.define(Bully.is, Bully);

Solution

  • The <paper-input> is already updating messaged through the two-way data binding (i.e., value="{{messaged}}"). In sendmsg(), you could read the value of messaged via this.messaged (not this.messaged.value).

    sendmsg() {
      console.log('messaged', this.messaged);
      this.messaged += ' SENT!';
    }
    

    demo