Load search results, cancel stale requests, and fetch the next page.

useAsyncOptions loads items as someone types. It waits for typing to pause, cancels requests that are replaced, and keeps the previous results visible while loading.

import { Component } from "@angular/core"
import { LucideCheck, LucideChevronDown } from "@lucide/angular"
import { useAsyncOptions } from "@ui-sdk/angular/async-options"
import {
  Combobox,
  ComboboxContent,
  ComboboxEmpty,
  ComboboxInput,
  ComboboxItem,
  ComboboxItemIndicator,
  ComboboxLabel,
  ComboboxList,
  ComboboxStatus,
  ComboboxTrigger,
} from "@ui-sdk/angular/combobox"

@Component({
  imports: [
    Combobox,
    ComboboxContent,
    ComboboxEmpty,
    ComboboxInput,
    ComboboxItem,
    ComboboxItemIndicator,
    ComboboxLabel,
    ComboboxList,
    ComboboxStatus,
    ComboboxTrigger,
    LucideCheck,
    LucideChevronDown,
  ],
  template: `
    <ng-container
      uiCombobox
      [items]="movies.state().items"
      defaultQuery="the"
      [filter]="false"
      [status]="movies.state().status"
      (beforeQueryChange)="movies.setQuery($event.value)"
    >
      <div data-slot="stack">
        <label uiComboboxLabel>Movie</label>
        <div data-slot="row">
          <input uiComboboxInput placeholder="Search movies…" />
          <button uiComboboxTrigger aria-label="Show movies">
            <svg lucideChevronDown></svg>
          </button>
        </div>
      </div>
      <div *uiComboboxContent>
        <div uiComboboxStatus #comboboxStatus="uiComboboxStatus">
          {{ comboboxStatus.state().status === 'error'
              ? 'Couldn't load movies.'
              : comboboxStatus.state().loading
                ? 'Searching…'
                : comboboxStatus.state().count + ' ' + (comboboxStatus.state().count === 1 ? 'movie' : 'movies') }}
        </div>
        <div uiComboboxEmpty #comboboxEmpty="uiComboboxEmpty">
          @if (comboboxEmpty.state().empty && !comboboxEmpty.state().loading) {
            No movies match “{{ comboboxEmpty.state().query }}”.
          }
        </div>
        <div uiComboboxList #comboboxList="uiComboboxList">
          @for (item of itemsOf(comboboxList.state().items); track item.value) {
            <div
              uiComboboxItem
              [value]="item.value"
              [label]="item.label"
              [disabled]="item.disabled"
            >
              {{ item.label }}
              <span *uiComboboxItemIndicator>
                <svg lucideCheck></svg>
              </span>
            </div>
          }
        </div>
      </div>
    </ng-container>
  `,
})
class Example {
  readonly movieTitles = [
    "The Shawshank Redemption",
    "The Godfather",
    "The Dark Knight",
    "Pulp Fiction",
    "Schindler's List",
    "The Lord of the Rings",
    "Fight Club",
    "Forrest Gump",
    "Inception",
    "The Matrix",
    "Goodfellas",
    "Interstellar",
    "Parasite",
    "Spirited Away",
    "Whiplash",
    "The Prestige",
    "The Departed",
    "Gladiator",
    "Alien",
    "Casablanca",
    "Amélie",
    "Arrival",
  ]

  readonly searchMovies = (
    query: string,
    { signal }: { signal: AbortSignal }
  ) => {
    return new Promise<{ value: string; label: string }[]>(
      (resolve, reject) => {
        const timer = setTimeout(() => {
          const needle = query.trim().toLowerCase()
          resolve(
            this.movieTitles
              .filter((title) => title.toLowerCase().includes(needle))
              .map((title) => ({
                value: title.toLowerCase().replace(/\W+/g, "-"),
                label: title,
              }))
          )
        }, 500)
        signal.addEventListener("abort", () => {
          clearTimeout(timer)
          reject(signal.reason)
        })
      }
    )
  }

  readonly movies = useAsyncOptions(this.searchMovies, {
    debounce: 300,
    query: "the",
    immediate: true,
  })

  itemsOf(items: unknown) {
    return items as { value: string; label: string; disabled?: boolean }[]
  }
}

export { Example }
Change the movie search and wait for the results. Use the arrow keys to choose a movie, then press Enter.

Load Results

Pass a loader to the helper in a field initializer. This example expects /api/movies to return an array of movie titles:

import { Component } from "@angular/core"
import { useAsyncOptions } from "@ui-sdk/angular/async-options"
import {
  Combobox,
  ComboboxContent,
  ComboboxInput,
  ComboboxItems,
} from "@ui-sdk/angular/combobox"

@Component({
  selector: "app-movie-search",
  imports: [Combobox, ComboboxContent, ComboboxInput, ComboboxItems],
  template: `
    <ng-container
      uiCombobox
      [items]="movies.state().items"
      [filter]="false"
      [status]="movies.state().status"
      (queryChange)="movies.setQuery($event)"
    >
      <input uiComboboxInput aria-label="Movie" placeholder="Search movies…" />
      <div *uiComboboxContent>
        <div uiComboboxItems></div>
      </div>
    </ng-container>
  `,
})
export class MovieSearch {
  readonly movies = useAsyncOptions<string>(async (query, { signal }) => {
    const response = await fetch(`/api/movies?q=${encodeURIComponent(query)}`, {
      signal,
    })
    if (!response.ok) throw new Error("Couldn't load movies")
    return response.json()
  })
}

movies.state is a signal, so the template follows each load. Pass signal to fetch so a newer search can cancel the request. The helper cancels when the component is destroyed. [filter]="false" leaves matching and ordering to the server.

Use uiComboboxStatus and uiComboboxEmpty to show loading, error, and empty messages, as in the demo. The same pattern works with Select, Autocomplete, and Command.

Choose When to Load

The second argument sets the starting behavior:

OptionWhat It DoesDefault
debounceMilliseconds typing must pause before a request starts.200
queryThe starting search text.""
immediateLoads that text as soon as the component renders in the browser.false
minLengthCharacters the text needs before anything loads. Shorter text clears the items.0

For initial choices, add { immediate: true, debounce: 300 } after the loader. Until that first load starts, status is already "loading", so the list never flashes an empty state. If you set query, use the same starting text for the component's defaultQuery.

Load More

For paged results, the loader receives page, starting at 0. Return { items, hasMore }:

import type { AsyncOptionsContext } from "@ui-sdk/angular/async-options"

async function loadMoviePages(
  query: string,
  { signal, page }: AsyncOptionsContext
) {
  const response = await fetch(
    `/api/movies?q=${encodeURIComponent(query)}&page=${page}`,
    { signal }
  )
  if (!response.ok) throw new Error("Couldn't load movies")
  const data: { titles: string[]; next: number | null } = await response.json()
  return { items: data.titles, hasMore: data.next !== null }
}

export { loadMoviePages }

Pass loadMoviePages to useAsyncOptions in place of the inline loader above.

Connect (loadMore)="movies.loadMore()" on the combobox. It asks for another page when scrolling or keyboard navigation reaches the last item. The helper appends the new items.

import { Component } from "@angular/core"
import { LucideCheck, LucideChevronDown } from "@lucide/angular"
import { useAsyncOptions } from "@ui-sdk/angular/async-options"
import {
  Combobox,
  ComboboxContent,
  ComboboxEmpty,
  ComboboxInput,
  ComboboxItem,
  ComboboxItemIndicator,
  ComboboxLabel,
  ComboboxList,
  ComboboxStatus,
  ComboboxTrigger,
} from "@ui-sdk/angular/combobox"

@Component({
  imports: [
    Combobox,
    ComboboxContent,
    ComboboxEmpty,
    ComboboxInput,
    ComboboxItem,
    ComboboxItemIndicator,
    ComboboxLabel,
    ComboboxList,
    ComboboxStatus,
    ComboboxTrigger,
    LucideCheck,
    LucideChevronDown,
  ],
  template: `
    <ng-container
      uiCombobox
      [items]="movies.state().items"
      [filter]="false"
      [status]="movies.state().status"
      (beforeQueryChange)="movies.setQuery($event.value)"
      (loadMore)="movies.loadMore()"
    >
      <div data-slot="stack">
        <label uiComboboxLabel>Movie</label>
        <div data-slot="row">
          <input uiComboboxInput placeholder="Search movies…" />
          <button uiComboboxTrigger aria-label="Show movies">
            <svg lucideChevronDown></svg>
          </button>
        </div>
      </div>
      <div *uiComboboxContent>
        <div uiComboboxEmpty #comboboxEmpty="uiComboboxEmpty">
          @if (comboboxEmpty.state().empty && !comboboxEmpty.state().loading) {
            No movies found.
          }
        </div>
        <div uiComboboxList #comboboxList="uiComboboxList">
          @for (item of itemsOf(comboboxList.state().items); track item.value) {
            <div
              uiComboboxItem
              [value]="item.value"
              [label]="item.label"
              [disabled]="item.disabled"
            >
              {{ item.label }}
              <span *uiComboboxItemIndicator>
                <svg lucideCheck></svg>
              </span>
            </div>
          }
        </div>
        <div uiComboboxStatus #comboboxStatus="uiComboboxStatus">
          {{
            comboboxStatus.state().loading
              ? "Loading more…"
              : movies.state().hasMore
                ? comboboxStatus.state().count + " loaded"
                : "All " + comboboxStatus.state().count
          }}
        </div>
      </div>
    </ng-container>
  `,
})
class Example {
  readonly movieTitles = [
    "The Shawshank Redemption",
    "The Godfather",
    "The Dark Knight",
    "Pulp Fiction",
    "Schindler's List",
    "The Lord of the Rings",
    "Fight Club",
    "Forrest Gump",
    "Inception",
    "The Matrix",
    "Goodfellas",
    "Interstellar",
    "Parasite",
    "Spirited Away",
    "Whiplash",
    "The Prestige",
    "The Departed",
    "Gladiator",
    "Alien",
    "Casablanca",
    "Amélie",
    "Arrival",
  ]

  readonly searchMoviePages = (
    query: string,
    { signal, page }: { signal: AbortSignal; page: number }
  ) => {
    return new Promise<{
      items: { value: string; label: string }[]
      hasMore: boolean
    }>((resolve, reject) => {
      const timer = setTimeout(() => {
        const needle = query.trim().toLowerCase()
        const found = this.movieTitles
          .filter((title) => title.toLowerCase().includes(needle))
          .map((title) => ({
            value: title.toLowerCase().replace(/\W+/g, "-"),
            label: title,
          }))
        resolve({
          items: found.slice(page * 5, page * 5 + 5),
          hasMore: found.length > page * 5 + 5,
        })
      }, 500)
      signal.addEventListener("abort", () => {
        clearTimeout(timer)
        reject(signal.reason)
      })
    })
  }

  readonly movies = useAsyncOptions(this.searchMoviePages, { immediate: true })

  itemsOf(items: unknown) {
    return items as { value: string; label: string; disabled?: boolean }[]
  }
}

export { Example }
Open the movie list and scroll down, or use Arrow Down to reach the last result. The next page is added to the list.

status is "loading" during a request, "error" after a failure, and "idle" otherwise. error holds the failure, and the previous items stay available.

Call movies.reload() from a retry button to load the current query again, starting at page 0. movies.state().hasMore tells you whether another page is available.