Search code examples
javascriptpolymerpolymer-2.xcustom-element

How to change the properties of a custom element in Polymer 2.0?


I'm trying to add paper-tabs custom element to my Polymer 2.0 app.

I'm having troubles changing the properties of the element. I want the first tab to be selected, so I'm trying to do it with this property

But when I added that "static get properties" script, the element just disappeared from the page.

What am I doing wrong?

Code

   <paper-tabs selected="{{selected}}">
      <paper-tab>tab1</paper-tab>
      <paper-tab>tab2</paper-tab>
      <paper-tab>tab3</paper-tab>
    </paper-tabs>

    <iron-pages selected="{{selected}}">
      <div>1</div>
      <div>2</div>
      <div>3</div>
    </iron-pages>

    class MyTabs extends Polymer.Element {
      static get is() { return 'my-tabs'; },

      static get properties() {
        return {
          selected: {
            value: 0,
          }, 
        },
      },
    }

Solution

  • I don't know exactly where your issue can be created.

    But you have to remove the comma after the static properties block, after the return block and your selected property need to have a "type" property that you are missing.

    Below this is my test element I created that worked :

    <link rel="import" href="bower_components/polymer/polymer-element.html">
    <link rel="import" href="bower_components/paper-tabs/paper-tabs.html">
    <link rel="import" href="bower_components/paper-tabs/paper-tab.html">
    <link rel="import" href="bower_components/iron-pages/iron-pages.html">
    
    <dom-module id="os-test">
        <template>
            <paper-tabs id="tabs" selected="{{tabSelected}}">
                <paper-tab>Tab 1</paper-tab>
                <paper-tab>Tab 2</paper-tab>
                <paper-tab>Tab 3</paper-tab>
            </paper-tabs>
    
            <iron-pages selected="{{tabSelected}}">
                <div>1</div>
                <div>2</div>
                <div>3</div>
            </iron-pages>
        </template>
        <script>
            class OsTestElement extends Polymer.Element {
                static get is() {
                    return 'os-test';
                }
    
                static get properties() {
                    return {
                        tabSelected: {
                            type: Number,
                            value: 0,
                            observer: "log"
                        }
                    }
                }
    
                log(tabID) {
                    console.log("selected tab : " + tabID);
                }
            }
            window.customElements.define(OsTestElement.is, OsTestElement);
        </script>
    </dom-module>
    

    The selected attribute will change every time you clicked on the tab. You can check the console to see the tab selected.

    If that doesn't help you, can you add more details.

    Thanks