# Angular

> Typed Angular skeleton loader components with server rendering, for Angular 22 and Angular SSR.

To show a skeleton loader in Angular, wrap the part of the page that loads in Dotquilt's `<dotquilt-region>`, put a loader such as `<dotquilt-skeleton-text [lines]="3" />` in an element marked `dotquiltPlaceholder`, and set its `state` from your data: `pending`, `refreshing` or `ready`.

`@dotquilt/angular` makes the native components standalone Angular components: each one's host is the native element itself. Templates are type-checked, with no `CUSTOM_ELEMENTS_SCHEMA`. They register themselves, render their placeholder on the server, and take their state from your inputs.

```sh
npm install @dotquilt/angular dotquilt
```

```ts
import { DotquiltPlaceholder, LoadingRegion, SkeletonText } from '@dotquilt/angular';
```

Import the components a template uses into its component's `imports`, with the `DotquiltPlaceholder` directive wherever you mark a placeholder: without it the build still passes, but the placeholder renders as content and never leaves. The package has one entry point: an Angular build keeps only the components you use.

## State comes from your data

A region needs only two things from you: whether the data is `pending`, `refreshing` or `ready`, and a `cycle` naming the current request. Keep the request in your own signals:

- **Start a new cycle per request**, such as the id you are loading. A stale answer for an older cycle can't settle a newer one.
- **Use `refreshing`** when you already show data and are fetching a newer copy: the content stays visible and usable.
- **On an error**, show your message with `state="ready"` and `[timing]="{ duration: 0 }"`, so it replaces the placeholder at once.

```ts title="team-list.ts"
import {
  afterNextRender,
  Component,
  DestroyRef,
  inject,
  signal,
} from '@angular/core';
import {
  DotquiltPlaceholder,
  LoadingRegion,
  SkeletonCircle,
  SkeletonLine,
} from '@dotquilt/angular';

interface Member {
  name: string;
  role: string;
}

@Component({
  selector: 'app-team-list',
  imports: [DotquiltPlaceholder, LoadingRegion, SkeletonCircle, SkeletonLine],
  template: `
    <section>
      <h2>Members</h2>
      <button type="button" (click)="reload()">Reload</button>
      <!-- An error replaces the placeholder at once, without the handoff. -->
      <dotquilt-region
        aria-label="Team members"
        [state]="status() === 'loading' ? 'pending' : 'ready'"
        [cycle]="cycle().toString()"
        [timing]="status() === 'failed' ? { duration: 0 } : undefined"
        (handoffEnd)="handovers.set(handovers() + 1)"
      >
        <div dotquiltPlaceholder>
          @for (row of [0, 1, 2]; track row) {
            <div class="member-skeleton">
              <dotquilt-skeleton-circle />
              <dotquilt-skeleton-line style="width: 45%" />
              <dotquilt-skeleton-line style="width: 30%" />
            </div>
          }
        </div>
        @if (status() === 'done') {
          @for (member of members(); track member.name) {
            <div class="member">
              <span class="avatar"></span>
              <h3>{{ member.name }}</h3>
              <p>{{ member.role }}</p>
            </div>
          }
        } @else if (status() === 'failed') {
          <p role="alert">We couldn't load the team. Try again later.</p>
        }
      </dotquilt-region>
      <p class="note">Handovers: {{ handovers() }}</p>
    </section>
  `,
})
export class TeamList {
  protected readonly status = signal<'loading' | 'done' | 'failed'>('loading');
  protected readonly members = signal<Member[]>([]);
  protected readonly cycle = signal(0);
  protected readonly handovers = signal(0);
  #latest: AbortController | undefined;

  constructor() {
    afterNextRender(() => this.load());
    inject(DestroyRef).onDestroy(() => this.#latest?.abort());
  }

  protected reload() {
    this.cycle.update((n) => n + 1);
    this.load();
  }

  private load() {
    // Only the latest request may update the list.
    this.#latest?.abort();
    const request = new AbortController();
    this.#latest = request;
    this.status.set('loading');
    fetch('/api/team', { signal: request.signal })
      .then((response) => {
        if (!response.ok) throw new Error(`Request failed: ${response.status}`);
        return response.json() as Promise<Member[]>;
      })
      .then((list) => {
        this.members.set(list);
        this.status.set('done');
      })
      .catch(() => {
        if (!request.signal.aborted) this.status.set('failed');
      });
  }
}
```

## Server rendering and hydration

With Angular SSR, the placeholder is in the first HTML, before any JavaScript runs, and `provideClientHydration()` keeps it. The elements register in the browser after rendering. Their styles before that go in the document head once, through Angular's own component styles.

Functions such as `targetProvider` and custom animations stay in the browser, so a chart's marks can glide onto the real line once it's there:

```ts title="revenue-chart.ts"
import {
  afterNextRender,
  Component,
  computed,
  DestroyRef,
  inject,
  signal,
} from '@angular/core';
import {
  ChartLoader,
  DotquiltPlaceholder,
  LoadingRegion,
} from '@dotquilt/angular';
import type { TargetProvider } from 'dotquilt/chart';

/** Where each value sits in a box of `width` × `height`. */
function linePoints(values: readonly number[], width: number, height: number) {
  const top = Math.max(...values) * 1.15;
  return values.map((value, i) => ({
    x: (i / Math.max(1, values.length - 1)) * width,
    y: height - (value / top) * height,
  }));
}

@Component({
  selector: 'app-revenue-chart',
  imports: [ChartLoader, DotquiltPlaceholder, LoadingRegion],
  template: `
    <dotquilt-region
      aria-label="Revenue by month"
      [state]="series() ? 'ready' : 'pending'"
    >
      <div dotquiltPlaceholder>
        <dotquilt-chart-loader
          variant="line"
          [targetProvider]="target"
          style="height: 160px"
        />
      </div>
      @if (series()) {
        <svg
          viewBox="0 0 320 160"
          preserveAspectRatio="none"
          style="display: block; width: 100%; height: 160px"
          role="img"
          aria-label="Revenue by month"
        >
          <path
            [attr.d]="path()"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            vector-effect="non-scaling-stroke"
          />
        </svg>
      }
    </dotquilt-region>
  `,
})
export class RevenueChart {
  protected readonly series = signal<number[] | null>(null);
  // Where the real line will be, in the loader's own size: the marks glide
  // onto it before the chart draws in.
  protected readonly target: TargetProvider = ({ width, height }) => {
    const series = this.series();
    return series
      ? {
          kind: 'line',
          points: linePoints(series, width, height),
          baseline: height,
        }
      : null;
  };
  protected readonly path = computed(() => {
    const series = this.series();
    return series
      ? linePoints(series, 320, 160)
          .map(
            ({ x, y }, i) => `${i ? 'L' : 'M'}${x.toFixed(1)} ${y.toFixed(1)}`,
          )
          .join(' ')
      : '';
  });

  constructor() {
    const request = new AbortController();
    afterNextRender(() => {
      fetch('/api/revenue', { signal: request.signal })
        .then((response) => response.json() as Promise<{ series: number[] }>)
        .then((body) => this.series.set(body.series))
        .catch(() => {});
    });
    inject(DestroyRef).onDestroy(() => request.abort());
  }
}
```

Router navigation works the same: a loader on the next page starts fresh, and its listeners go when the page does.

## Outputs and the element

Each component has the outputs `(handoffStart)`, `(handoffEnd)`, `(handoffCancel)` and `(loaderError)`, with the native `CustomEvent`: `$event.detail.reason` says how a handoff ended. A component's `element` is the native element, if you need its methods. A component that leaves with a leave animation is destroyed before its element leaves the page, so it doesn't report the `handoffCancel` that removal causes.

While pending, render no content in the region (`@if` on the data), so the placeholder holds its own size.

## Styles and CSP

Angular adds the components' styles with your app's `CSP_NONCE` (or `ngCspNonce`), and the elements use the same nonce for their own styles unless you pass a `stylePolicy`. For an external stylesheet instead, pass `{ mode: 'external', href }` and serve the file from `@dotquilt/angular/styles/`. See [Content Security Policy](/docs/guides/csp/).

## The native elements in Angular templates

You can also use the native elements directly, without `@dotquilt/angular`: add `CUSTOM_ELEMENTS_SCHEMA` to the component's `schemas`, register the elements once in the browser, and bind objects such as a table's `columns` as properties (`[columns]="columns"`). Angular then doesn't type-check those bindings, and the native elements have no placeholder in the server HTML: it appears once they register.
