简体   繁体   中英

this.shadowRoot.querySelector('#upload') return always null Polymer 2.x

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 .

控制台屏幕截图

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM