Search code examples
polymerweb-componentcustom-element

How to change app route location from child element


I created app-route based project. Certain event I need to change the route to different root.

index.html

<my-app></my-app>

my-app.html

<!-- this app-route manages the top-level routes -->
<app-route
    route="{{route}}"
    pattern="/:view"
    data="{{routeData}}"
    tail="{{subroute}}"></app-route>

<!-- iron-pages selects the view based on the active route -->
<iron-pages selected="[[routeData.view]]" attr-for-selected="name">
  <landing-app name="home" route="{{subroute}}"></landing-app>
  <dashboard-app name="dashboard" route="{{subroute}}"></dashboard-app>
</iron-pages>

landing-app.html

When handler called I need to change the route to dashboard. How to do that ?

<dom-module id="landing-app">
  <template>
    <button on-click="_handlerCall">Change to Dashboard</button>
  </template>
  <script>
    class LandingApp extends Polymer.Element {

      static get is() {return 'landing-app'}

      _handlerCall() {
        this.set('route.path', '/dashboard') // but no luck :(
      }
    }
    customElements.define(LandingApp.is, LandingApp);
  </script>
</dom-module>

Solution

  • Add: <app-location route="{{route}}"></app-location> after <template> in landing-app.html

    <dom-module id="landing-app">
      <template>
        <app-location route="{{route}}"></app-location>
        <button on-click="_handlerCall"> Change to Dashboard</button>
      </template>
      <script>
        class LandingApp extends Polymer.Element {
    
          static get is() {return 'landing-app'}
    
          _handlerCall() {
            this.set('route.path', '/dashboard') // :)
          }
        }
        customElements.define(LandingApp.is, LandingApp);
      </script>
    </dom-module>
    

    Documentation for app-location: https://www.webcomponents.org/element/PolymerElements/app-route/elements/app-location