1

I'm having trouble accessing an element in the following dom-if template to add a custom event listener:

<template is="dom-if" if=[[!uploaded]]>
    <vaadin-upload id="upload" target="http://localhost:3000/uploadFile" form-data-name="doc" max-files="1">
        <iron-icon slot="drop-label-icon" icon="description"></iron-icon>
        <span slot="drop-label">....</span>
    </vaadin-upload>
</template>
<template is="dom-if" if="[[uploaded]]">
      <pdf-element src=[[....]]></pdf-element>
</template> 

I tried to add event listeners for upload-response and upload-success in the connectedCallback this way:

connectedCallback() {
    super.connectedCallback();
    console.log(this.shadowRoot.querySelector('#upload'))
    this.shadowRoot.querySelector('#uploadFile').addEventListener('upload-response', event=>this._uploadFile(event))
    this.shadowRoot.querySelector('#uploadFile').addEventListener('upload-success', event=>this._uploadFileSuccessful(event))
  }

The uploaded property is false by default. I searched in the Polymer 2.0 docs, and didn't find a way to make it work. I always get null.

console screenshot

I have already used this.shadowRoot.querySelector in dom-repeat template without a problem. How do I make querySelector work with the dom-if?

tony19
  • 125,647
  • 18
  • 229
  • 307

1 Answers1

2

The <dom-if> contents aren't yet stamped in the connectedCallback even though the if condition is true, so you'd have to wait until the next render-frame with Polymer.RenderStatus.afterNextRender():

Polymer.RenderStatus.afterNextRender(this, () => {
  const uploader = this.shadowRoot.querySelector('#upload');
  uploader.addEventListener('upload-success', () => { /* ... */ });
});

demo

tony19
  • 125,647
  • 18
  • 229
  • 307