Wednesday, November 14, 2018

Polymer Component Visibility Change Handling

I was working on a web app using Polymer's routing and I needed to know when the view changed to my component so that I could do certain things, like set the focus on a particular control.

There's a ready() method in the PolymerElement base class that you can override, but it only gets called the first time the component is shown. I needed it to get called every time the component is shown. So that doesn't work.

The key is to set selected-attribute on the iron-pages element. I set it to "visible". This will cause it to set a visible property on your view's component to true or false, depending on if the component is visible.


<iron-pages selected="[[page]]"
  attr-for-selected="name"
  selected-attribute="visible"
  role="main">
  <my-view name="my-view"></my-view>
</iron-pages>

Note that we don't need to set a visible attribute on the <my-view> component because it automatically gets passed into it.

Next thing to do is go into the view component and add a visible property definition whose type is Boolean. We also need to make it an observed property so we get notified when it changes.

class MyView extends PolymerElement {
  static get properties() {
    return {
      visible: {
        type: Boolean,
        observer: '_visibleChanged'
      }
    }
  }

Now whenever the visibility of the component changes it will call the _visibleChanged() method passing in true or false as the first parameter.

  _visibleChanged(visible) {
    if (visible) {
      // do something...
    }
  }

That's all there is to it. I figured it out from this article, which is (relatively) old and I think out of date for Polymer 3. It didn't quite work the way that article explained and this way seems a lot simpler.

Code hard!

No comments:

Post a Comment