Retain element size when show.bind hides it

Suppose your element with show.bind is bounded to a property name isVisible:

import { observable } from 'aurelia-framework';

class ABC {
  
  // populated by Aurelia ref binding
  readonly element: HTMLElement;
 // this is the cache for element size before it gets display: none
  elementRectSnapshot: ClientRect;

  @observable()
  isVisible: boolean;

  isVisibleChanged(newValue: boolean) {
    // element reference will only be available after bind lifecycle
    // so we do nothing when element is not available
    if (!this.element) {
      return;
    }
    // If new value is falsy,
    // the element it's bound with will be hidden
    if (!newValue) {
      this.elementRectSnapShot = this.element.getBoundingClientRect();
    }
  }
}

Why it works: changeHandler of @observable is called synchronously, thus will be executed before bindings. Which means isVisibleChanged will be executed before the element gets hidden, so the size should be valid. For more on difference between @observable and @bindable, you can have a look at Difference between @observable and @bindable

1 Like