Search code examples
javascriptpolymer-2.xpaper-dialog

open paper-dialog from another component


I'm using polymer 2 and the paper-dialog component.

I have another custom web component which when a button is clicked it needs to display a paper-dialog which is in another component.

From the below test components you can see that:

The click event calls:

showDialog()
{
    var testDialog = new TestDialog();
    testDialog.open();
}

Which then calls:

open()
{
    this.$.dialog.open();
}

The error I get is that this.$ is undefined.

Now this does make some sense as I assume that $ isn't populated until the template is rendered.

So I guess the question is how do I get the dialog template to render so that I can then open it?

Calling component:

    <link href="../../../bower_components/polymer/polymer.html" rel="import">
<link rel="import" href="test-dialog.html">

<dom-module id="time-display-test">
    <template>
        <style include="shared-styles">

        </style>

<button id="time" >Show</button>
</template>

    <script>
        class TimeDisplay extends Polymer.Element {
            static get is() {
                return 'time-display-test';
            }

            static get properties() {
             return {
                };
            }


            connectedCallback()
            {
                super.connectedCallback();

                this.$.time.onclick = ()=>{ this.showDialog(); };
            }

            showDialog()
            {
                var testDialog = new TestDialog();
                testDialog.open();
            }

        }
        customElements.define(TimeDisplay.is, TimeDisplay);
    </script>
</dom-module>

The paper dialog component:

    <link rel="import"     href="../../../bower_components/polymer/polymer.html">
<link rel="import" href="../../../bower_components/paper-dialog/paper-dialog.html">

<dom-module id="test-dialog">
    <template>
        <style include="shared-styles">
        </style>
        <!-- backdrop autoCloseDisable -->
        <paper-dialog id="dialog">
            <paper-dialog-scrollable>
                    Hello World
            </paper-dialog-scrollable>
        </paper-dialog>
    </template>

    <script>
        class TestDialog extends Polymer.Element {

            static get is() {
                return 'test-dialog';
            }

            static get properties() {
                return {

                };
            }

            open()
            {
                this.$.dialog.open();
            }


        }
        customElements.define(TestDialog.is, TestDialog);


    </script>
    </dom-module>

Solution

  • You must first append the new component to the dom to access it´s dom. this.$.* will only be initialized when the component was appended to the dom.

    showDialog()
    {
        var testDialog = new TestDialog();
        this.appendChild(testDialog);
        testDialog.open();
    }