Moazzam
Moazzam

Reputation: 429

unable to access content of node in dom-if in polymer 2.x

I am using polymer 2.0. I have rendering following collapsible content on page:

    <template is="dom-if" if="[[smallScreen]]">
        <iron-selector selected="[[page]]" attr-for-selected="name" class="drawer-list" role="navigation">
          <a>
            <span>users</span>
            <paper-icon-button icon="icons:expand-more" on-tap="expandClicked" role="button" aria-controls="collapse"></paper-icon-button>
          </a>
          <iron-collapse id="collapse">
            <a name="user-overview" href="#/usr/user-overview">user Overview</a>
            <a name="user-history" href="#/usr/user-history">user History</a>
            <a name="user-detail" href="#/isr/user-detail">user Detail</a>
          </iron-collapse>            
        </iron-selector>
    </template>

Below is the Polymer script:

    expandClicked(event) {
        this.$.collapse.toggle();
    }

When I click element to collapse/expand it, then below error is reported in browser console:

user-app.js:49 Uncaught TypeError: Cannot read property 'toggle' of undefined
    at HTMLElement.expandClicked (user-app.js:49)
    at HTMLElement.handler (template-stamp.html:92)
    at Object._fire (gestures.html:535)
    at Object.forward (gestures.html:830)
    at Object.click (gestures.html:811)
    at HTMLElement._handleNative (gestures.html:333)

Please guide as how to access dom-if nodes in polymer script to expand or collapse them.

Upvotes: 1

Views: 535

Answers (1)

a1626
a1626

Reputation: 2964

The reason why Polymer is throwing the error is that your iron-collapse is not a static node it's a dynamic node.

Anything that is inside another template is dynamic node and this.$ can be used only for static node.

In order to search for dynamic node you should use this.shadowRoot.querySelector(selector).

You can check the documentation for more details.

Upvotes: 1

Related Questions