Preselect a default page in iron-pages when using with paper-tabs
Asked Answered
B

3

6

I am using Polymer iron-pages along with paper-tabs in my rails app. The problem is none of pages were shown until one of the paper-tabs was clicked. I want the first page in iron-pages to be selected by default without user interaction.

I have put both paper-tabs and iron-pages in a <template is='dom-bind'></template>. Have read documentation about data binding, But I couldn't figure out how to achieve this. Please somebody suggest your valuable suggestions. Thank you.

<template is="dom-bind">
  <div class="middle">
    <paper-tabs class="bottom self-end" selected="{{selected}}">
      <paper-tab>Page 1</paper-tab>
      <paper-tab>Page 2</paper-tab>
    </paper-tabs>
  </div>
  <div class="bottom">
    <iron-pages selected="{{selected}}">
      <div> Page 1(This should be selected by default.)
      </div>
      <div> Page 2
      </div>
    </iron-pages>
  </div>
</template>
Burgeon answered 10/6, 2015 at 10:51 Comment(0)
D
8

Since you're working with an auto-binding template, simply add a short script that sets the selected property of your <iron-pages> element at load time. For example (assuming you are using webcomponents-lite.js):

<template is="dom-bind">
  <div class="middle">
    <paper-tabs class="bottom self-end" selected="{{selected}}">
      <paper-tab>Page 1</paper-tab>
      <paper-tab>Page 2</paper-tab>
    </paper-tabs>
  </div>
  <div class="bottom">
    <iron-pages selected="{{selected}}">
      <div> Page 1 (This will be selected by default.)
      </div>
      <div> Page 2
      </div>
    </iron-pages>
  </div>
</template>

<script>
  document.addEventListener('WebComponentsReady', function () {
    var template = document.querySelector('template[is="dom-bind"]');
    template.selected = 0; // selected is an index by default
  });
</script>
Deranged answered 10/6, 2015 at 11:18 Comment(0)
O
7

If you are using Polymer you can also set the default view by defining it in the Polymer properties of your web component:

Polymer({
  is: 'your-web-component',

  properties: {
    selected: {
        value: 0
    }
  }
});
Osteoclast answered 17/7, 2016 at 20:43 Comment(0)
C
0

Use the custom element's constructor() to set the property to name of the tab that should be selected

<paper-tabs id="choiceTab" style="width:400px;" attr-for-selected='name' selected="{{choice}}">
                    <paper-tab name="tab1">Tab 1</paper-tab>
                    <paper-tab name="tab2">Tab 2</paper-tab>

                </paper-tabs>

.....

static get properties() {
            return {
                choice: {
                    type: String,
                    reflectToAttribute: true
                }
            };
        }

.....

constructor() {
                super();
                this.choice = 'tab1';
            }
Charmian answered 15/12, 2017 at 2:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.