首页 > 解决方案 > 从另一个组件打开纸质对话框

问题描述

我正在使用聚合物 2 和纸质对话组件。

我有另一个自定义 Web 组件,当单击按钮时,它需要显示另一个组件中的纸质对话框。

从下面的测试组件中您可以看到:

点击事件调用:

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

然后调用:

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

我得到的错误this.$是未定义的。

现在这确实有些道理,因为我假设在呈现模板之前不会填充 $ 。

所以我想问题是如何让对话框模板呈现以便我可以打开它?

调用组件:

    <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>

纸质对话框组件:

    <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>

标签: javascriptpolymer-2.xpaper-dialog

解决方案


您必须首先将新组件附加到 dom 才能访问它的 dom。this.$.* 只会在组件附加到 dom 时被初始化。

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

推荐阅读