Asynchronous loading in custom elements

I am building a custom element which is basically a group of HTML <select>s. The options should be fetched from the backend via Promises and always come from the exact same source, while the selected values are directly bound to an object’s properties.

However, it seems components lack potentially asynchronous hooks during their building licefycle, unlike the activate hook of routable pages. I tried putting the backend calls in bind, but while the data does get loaded the association with the original selected values gets lost. created also does not seem to be asynchronous, at least according to the TypeScript type definitions.

I could load the options in the containing pages and bind them to the component, but since in this case the data sources are always going to be the same it would be somewhat cumbersome.

Right now, is there any way to force a component to wait for the loading promises to be fulfilled?


you can make the lifecycle methods async. once your property is set the repeat.for will bind your options.

typescript class

  public options: string[];
  public async bind() {
    this.options = await this.optionsService.get();

template view

<select value.bind="selected">
  <option repeat.for="option of options" value.bind="option">${option}</option>
1 Like

I had actually tried that and I just tried that again, but the actual loading is performed later than needed (in the current implementation the viewModel contains a getter which needs the option lists to be already present; async bind does not work and neither does created).
I should note that my description of our use case was simplified (e.g. we use a wrapper component over the native <select>), so the problem could be elsewhere. Guess I’ll have to put more thought into this.

1 Like


You could try CompositionTransaction .
But i don’t know, if that approach is dated and what the standard way to solve this would be.
The question seems to show up once in a while and sadly i haven’t seen a “This is the Aurelia-Way to do it” answer yet. Maybe in V2 we’ll use an async binding and put a spinner on the select while the options are resolving. shrug


1 Like

Thank you for your answers.

After some tests I found out simply using an if.bind="options" on the inner component works (that is, wait until the options are loaded before actually attaching the select). This can cause some layout thrashing, but in our case it seems fine enough.
I suppose using a BindingSignaler for this purpose could also work.