How to highlight selected routerLink text on page reload, in Polymer3.x ?

242 Views Asked by At

I am building a Polymer3 music app, which fetches playlists from public api. All the playlistNames are implemented as routerLinks.

On clicking, the playlistName is getting bold, but on page reload the routerLink is not highlighted(bold).

For example: If i am entering localhost:8081/playlist1 in URL, then playlist1 should be bold, on page reload.

Thanks in advance.

routerLinks not highlighted

static get template() {
    return html `

      <app-location route="{{route}}" url-space-regex="^[[rootPath]]">
      </app-location>

      <app-route route="{{route}}" pattern="[[rootPath]]:page" data="{{routeData}}" tail="{{subroute}}">
      </app-route>

      <app-drawer-layout fullbleed="" narrow="{{narrow}}">
        <!-- Drawer content -->
        <app-drawer id="drawer" slot="drawer" swipe-open="[[narrow]]">
          <app-toolbar>Menu</app-toolbar>
          <iron-selector selected="[[page]]" attr-for-selected="name" class="drawer-list" role="navigation">
            <template is="dom-repeat" items="[[playlists]]">
              <a name="[[item.name]]" href="[[rootPath]][[item.name ]]">[[item.name]]</a>
            </template>
          </iron-selector>
        </app-drawer>

    `;
  }

1

There are 1 best solutions below

0
On

On clicking, the playlistName is getting bold, but on page reload the routerLink is not highlighted(bold).

This happens probably because of IronSelectableBehaviour present in the iron-selector element, which I believe applies the bold style on-tap. This also happens for paper-tabs for example.

So, the bold style is being applied because you're tapping the item. However, if you go to a page directly through the URL, you didn't actually click the item, that's why you're not getting the same behaviour.

Solution:

You will always have the class iron-selected on the current active item, whether through URL or on tap.

From the documentation:

iron-selector is not styled. Use the iron-selected CSS class to style the selected element.

Try it out

  <style>
    .iron-selected {
      background: #eee;
    }
  </style>