2017-06-26 48 views
1

如何使用來自iron-form的響應數據來觸發dom-if模板?如果有數據返回,我想顯示模板。此代碼不起作用。我在這裏做錯了什麼?聚合物2.0鐵形式響應觸發器dom-if

<link rel="import" href="../components/polymer/polymer-element.html"> 
<link rel="import" href="../components/polymer/lib/elements/dom-if.html"> 
<link rel="import" href="../components/iron-form/iron-form.html"> 

<dom-module id="a-tag"> 
    <template> 
    <iron-form> 
     <form action="/" method="get"> 
     <input name="test"> 
     <button></button> 
     </form> 
    </iron-form> 

    <template class="iftemplate" is="dom-if" if="[[data]]"> 
     <p>HELLO</p> 
    </template> 
    </template> 

    <script> 
    class ATag extends Polymer.Element { 
     static get is() {return 'a-tag'} 
     ready() { 
     super.ready() 
     this.shadowRoot.querySelector('iron-form').addEventListener('iron-form-response', (event) => { 
      this.shadowRoot.querySelector('.iftemplate').data = event.detail.response 
     }) 
     } 
    } 
    customElements.define(ATag.is, ATag) 
    </script> 
</dom-module> 

回答

2

您在這裏做很多錯誤的事情,

首先,我會建議一個id添加到窗體元素iron-form這樣你就可以在你的高分子元素的代碼輕鬆一點。

<iron-form id="my-form"> 
    ... 
</iron-form> 

,並添加事件監聽器這樣的:

this.$['my-form'].addEventListener('iron-form-response', ...); 

而且你正試圖屬性data添加到模板dom-if我不明白爲什麼。 [[data]]引用元素範圍內的屬性。你必須在正確的部分定義這個屬性。

static get properties() { 
    return { 
    data: { 
     type: String, 
     value: '' 
    } 
    }; 
} 

和事件偵聽器回調:

ready() { 
    super.ready() 

    this.$['my-form'].addEventListener('iron-form-response', (event) => { 
    // this.data = event.detail.response; 
    this.data = 'some data'; // for testing 
    }); 
}