Search code examples
polymerweb-componentpolymer-1.0

Polymer - Change page title with iron-pages


Lets say I have the demo implementation of iron-pages (from its Github page):

<iron-pages selected="0">
  <div>One</div>
  <div>Two</div>
  <div>Three</div>
</iron-pages>

<script>
  document.addEventListener('click', function(e) {
    var pages = document.querySelector('iron-pages');
    pages.selectNext();
  });
</script>

Now, I want to add a suffix to the page title to reflect the selected page. So for <div>One</div> I would like to append - selected One and so on.

What I've got so far is to make the change in routing.html when the route has been selected but it seems a bit weird to make the change here. Are there any other ways of doing this?


Solution

  • You should take a look at my Polymer component <page-title> here: https://github.com/zacharytamas/page-title/. You can install it with Bower, too:

    bower install page-title --save
    

    Likely you'd want some kind of function that maps the selected index from <iron-pages> to text you want to show as the title. In your example you could just the innerText of the selected element, but in practice your <iron-pages> elements would actually have content in them.

    This will depend on your setup but you could use my component to easily bind them, something like this:

    <dom-module id="my-app">
      <template>
    
        <page-title base-title="My Website" 
          title="[[selectedPage.title]]"></page-title>
    
        <iron-pages selected-item="{{selectedPage}}">
          <div title="First Page">One</div>
          <div title="Second Page">Two</div>
          <div title="Third Page">Three</div>
        </iron-pages>
    
      </template>
      <script>
        Polymer({
          is: 'my-app'
        });
      </script>
    </dom-module>
    

    Here I've just done some fanciness to bind the title of the page to the title attribute of the currently selected element from the <iron-pages>. It works pretty well! You may have to adopt to your situation but this should get you going.