LogoLogo
HomeDiscourseBlogDiscord
  • Introduction
  • Introduction
    • Quick start
    • Aurelia for new developers
    • Hello world
      • Creating your first app
      • Your first component - part 1: the view model
      • Your first component - part 2: the view
      • Running our app
      • Next steps
  • Templates
    • Template Syntax
      • Attribute binding
      • Event binding
      • Text interpolation
      • Template promises
      • Template references
      • Template variables
      • Globals
    • Custom attributes
    • Value converters (pipes)
    • Binding behaviors
    • Form Inputs
    • CSS classes and styling
    • Conditional Rendering
    • List Rendering
    • Lambda Expressions
    • Local templates (inline templates)
    • SVG
  • Components
    • Component basics
    • Component lifecycles
    • Bindable properties
    • Styling components
    • Slotted content
    • Scope and context
    • CustomElement API
    • Template compilation
      • processContent
      • Extending templating syntax
      • Modifying template parsing with AttributePattern
      • Extending binding language
      • Using the template compiler
      • Attribute mapping
  • Getting to know Aurelia
    • Routing
      • @aurelia/router
        • Getting Started
        • Creating Routes
        • Routing Lifecycle
        • Viewports
        • Navigating
        • Route hooks
        • Router animation
        • Route Events
        • Router Tutorial
        • Router Recipes
      • @aurelia/router-lite
        • Getting started
        • Router configuration
        • Configuring routes
        • Viewports
        • Navigating
        • Lifecycle hooks
        • Router hooks
        • Router events
        • Navigation model
        • Transition plan
    • App configuration and startup
    • Enhance
    • Template controllers
    • Understanding synchronous binding
    • Dynamic composition
    • Portalling elements
    • Observation
      • Observing property changes with @observable
      • Effect observation
      • HTML observation
      • Using observerLocator
    • Watching data
    • Dependency injection (DI)
    • App Tasks
    • Task Queue
    • Event Aggregator
  • Developer Guides
    • Animation
    • Testing
      • Overview
      • Testing attributes
      • Testing components
      • Testing value converters
      • Working with the fluent API
      • Stubs, mocks & spies
    • Logging
    • Building plugins
    • Web Components
    • UI virtualization
    • Errors
      • 0001 to 0023
      • 0088 to 0723
      • 0901 to 0908
    • Bundlers
    • Recipes
      • Apollo GraphQL integration
      • Auth0 integration
      • Containerizing Aurelia apps with Docker
      • Cordova/Phonegap integration
      • CSS-in-JS with Emotion
      • DOM style injection
      • Firebase integration
      • Markdown integration
      • Multi root
      • Progress Web Apps (PWA's)
      • Securing an app
      • SignalR integration
      • Strongly-typed templates
      • TailwindCSS integration
      • WebSockets Integration
      • Web Workers Integration
    • Playground
      • Binding & Templating
      • Custom Attributes
        • Binding to Element Size
      • Integration
        • Microsoft FAST
        • Ionic
    • Migrating to Aurelia 2
      • For plugin authors
      • Side-by-side comparison
    • Cheat Sheet
  • Aurelia Packages
    • Validation
      • Validation Tutorial
      • Plugin Configuration
      • Defining & Customizing Rules
      • Architecture
      • Tagging Rules
      • Model Based Validation
      • Validation Controller
      • Validate Binding Behavior
      • Displaying Errors
      • I18n Internationalization
      • Migration Guide & Breaking Changes
    • i18n Internationalization
    • Fetch Client
      • Overview
      • Setup and Configuration
      • Response types
      • Working with forms
      • Intercepting responses & requests
      • Advanced
    • Event Aggregator
    • State
    • Store
      • Configuration and Setup
      • Middleware
    • Dialog
  • Tutorials
    • Building a ChatGPT inspired app
    • Building a realtime cryptocurrency price tracker
    • Building a todo application
    • Building a weather application
    • Building a widget-based dashboard
    • React inside Aurelia
    • Svelte inside Aurelia
    • Synthetic view
    • Vue inside Aurelia
  • Community Contribution
    • Joining the community
    • Code of conduct
    • Contributor guide
    • Building and testing aurelia
    • Writing documentation
    • Translating documentation
Powered by GitBook
On this page
  • Basic implementation
  • Working with polyfill
  • Example usage
  • Special note:

Was this helpful?

Export as PDF
  1. Developer Guides
  2. Playground
  3. Custom Attributes

Binding to Element Size

Basic implementation

import { bindable, BindingMode, customAttribute } from 'aurelia';

@customAttribute({
  name: 'rectsize',
  hasDynamicOptions: true
})
export class RectSize {

  public static inject = [INode];

  @bindable({ mode: BindingMode.fromView })
  public value!: ResizeObserverSize;

  @bindable()
  public boxSize!: 'border-box' | 'content-box';

  private observer!: ResizeObserver;

  constructor(
    private readonly element: HTMLElement
  ) {

  }

  public binding(): void {
    let observer = this.observer;
    if (observer === void 0) {
      observer = this.observer = this.createObserver();
    }
    observer.observe(this.element, { box: 'border-box' });
  }

  public unbinding(): void {
    this.observer.disconnect();
    this.observer = (void 0)!;
  }

  private createObserver(): ResizeObserver {
    return new ResizeObserver((entries) => {
      this.handleResize(entries[0]);
    });
  }

  /**
   * @internal
   */
  private handleResize(entry: ResizeObserverEntry): void {
    this.value = this.boxSize === 'content-box' ? entry.contentBoxSize : entry.borderBoxSize;
  }
}

Working with polyfill

As ResizeObserver is still new and experimental API, it's not widely supported in all browsers. Fortunately there are a few polyfills available. For example:

To make the attribute work seamlessly with any polyfill users want to choose, we can adjust the way we get the ResizeObserver constructor, as shown in the following example:

export class RectSize {

+  /**
+   * Allow user to ponyfill Resize observer via this static field
+   */
+  public static ResizeObserver: ResizeObserver;


+  private createObserver(): ResizeObserver {
+    const ResizeObserverCtor = this.getResizeObserver();
-    return new ResizeObserver((entries) => {
+    return new ResizeObserverCtor((entries) => {
+      this.handleResize(entries[0]);
+    });
+  }


+  private getResizeObserver(): ResizeObserver {
+    return RectSize.ResizeObserver || window.ResizeObserver;
+  }

And now, our user can switch to any polyfill as the following example:

import { RectSize } from './some-path'
import { ResizeObserver } from 'some-resize-observer-polyfill'

RectSize.ResizeObserver = ResizeObserver;

Example usage

For the above implementation, the usage would be:

<form rectsize.bind="formSize">
  ...
</form>
or
<form rectsize="value.bind: formSize; box-model: content-box;">
  ...
</form>

Special note:

  private handleResize(entry: ResizeObserverEntry): void {
-    this.value = this.boxSize === 'content-box' ? entry.contentBoxSize : entry.borderBoxSize;
+    this.value = entry.contentRect;
  }
PreviousCustom AttributesNextIntegration

Last updated 1 year ago

Was this helpful?

older spec, with only contentRect:

newer spec, with supports for box model options:

For the polyfill at , you cannot use box-model for observation option, as it follows an older spec of ResizeObserver. Though it is a mature polyfill, and works well so if you want to use it, slightly modify the above implementation:

https://github.com/que-etc/resize-observer-polyfill
https://github.com/juggle/resize-observer
https://github.com/que-etc/resize-observer-polyfill