Await repeat.for rendering finish

Just wanted to share an easy trick in case you need to know when repeat.for finished rendering

import { customElement, noView } from 'aurelia-templating';
import { bindable } from 'aurelia-typed-observable-plugin';

@customElement('promise-resolver')
@noView
export class PromiseResolver {
  @bindable
  resolve: (value: unknown) => void;
  resolveChanged() {
    if (this.resolve) {
      this.resolve(undefined);
    }
  }

  // eslint-disable-next-line @typescript-eslint/no-empty-function
  bind() { }

  attached() {
    this.resolveChanged();
  }
}

Usage example

<div repeat.for="i of items">
  ${i}
  <promise-resolver resolve.bind="lastItemRendered" if.bind="$last"></promise-resolver>
</div>
items: number[];
lastItemRendered: (value: unknown) => void;

async loadItems() {
  this.items = [1,2,3];
  await new Promise(resolve => this.lastItemRendered = resolve);
  // do something after the items have been rendered
}
5 Likes