Skip to content
.md

Building with Angular

In this tutorial, you build a product browser in Angular: a search field, category checkboxes with facet counts, and a result list that updates on every change. dcupl runs in the browser; the component keeps its results in signals, so it works in a zoneless app, which is what ng new creates.

Time required: 15 minutes

What you will build: an Angular app with one dcupl instance shared through a service, and a catalog component that filters it.

For a complete app that loads a Console project, with a filter bar, paging and a results table, see the dcupl Angular starter on GitHub.

Prerequisites

Step 1: create an Angular project

Create a project and install dcupl. @dcupl/common holds the TypeScript types:

terminal
npx @angular/cli@latest new dcupl-angular --defaults --style=css --ssr=false
cd dcupl-angular
npm install @dcupl/core@2 @dcupl/common@2

--defaults skips the prompts. The new project has no zone.js: Angular updates the view when a signal the template reads changes.

Step 2: define the model and the data

The model and a few products live in one file. Step 6 shows how to load them from the Console instead.

src/app/dcupl/products.ts
import type { ModelDefinition } from '@dcupl/common';

export type Product = {
  key: string;
  name: string;
  category: string;
  price: number;
};

export const productModel: ModelDefinition = {
  key: 'Product',
  properties: [
    { key: 'name', type: 'string' },
    { key: 'category', type: 'string' },
    { key: 'price', type: 'float' },
  ],
};

export const products: Product[] = [
  { key: 'p1', name: 'Wireless Headphones', category: 'Electronics', price: 299.99 },
  { key: 'p2', name: 'Mechanical Keyboard', category: 'Electronics', price: 149.99 },
  { key: 'p3', name: 'Running Shoes', category: 'Sports', price: 129.99 },
  { key: 'p4', name: 'Coffee Maker', category: 'Home', price: 89.99 },
  { key: 'p5', name: 'Yoga Mat', category: 'Sports', price: 39.99 },
  { key: 'p6', name: 'Smart Watch', category: 'Electronics', price: 249.99 },
  { key: 'p7', name: 'Desk Lamp', category: 'Home', price: 49.99 },
  { key: 'p8', name: 'Water Bottle', category: 'Sports', price: 24.99 },
];

Step 3: share one instance through a service

A root service creates the instance once and hands every caller the same promise. init() parses the models and the data, so run it once per app, not per component:

src/app/dcupl/dcupl.service.ts
import { Injectable } from '@angular/core';
import { Dcupl } from '@dcupl/core';
import { productModel, products } from './products';

@Injectable({ providedIn: 'root' })
export class DcuplService {
  private ready?: Promise<Dcupl>;

  /** Creates the instance and runs init() once; a failed load is retried on the next call. */
  instance(): Promise<Dcupl> {
    this.ready ??= this.load().catch((error: unknown) => {
      this.ready = undefined;
      throw error;
    });
    return this.ready;
  }

  private async load(): Promise<Dcupl> {
    const dcupl = new Dcupl();
    dcupl.models.set(productModel);
    dcupl.data.set(products, { model: 'Product' });
    // init() resolves false instead of throwing
    if (!(await dcupl.init())) throw new Error('dcupl.init() failed');
    return dcupl;
  }
}

Step 4: build the catalog component

The component creates a list for the Product model and copies its result into signals whenever the result changes. The filter methods only change the list's query; onResultChange does the rest:

src/app/catalog/catalog.ts
import { Component, DestroyRef, inject, signal } from '@angular/core';
import type { DcuplList } from '@dcupl/core';
import { DcuplService } from '../dcupl/dcupl.service';
import type { Product } from '../dcupl/products';

type CategoryOption = { value: string; size: number; selected: boolean };

@Component({
  selector: 'app-catalog',
  templateUrl: './catalog.html',
  styleUrl: './catalog.css',
})
export class Catalog {
  private readonly dcuplService = inject(DcuplService);
  private list?: DcuplList<Product>;

  protected readonly status = signal<'loading' | 'ready' | 'error'>('loading');
  protected readonly items = signal<Product[]>([]);
  protected readonly total = signal(0);
  protected readonly categories = signal<CategoryOption[]>([]);

  constructor() {
    let destroyed = false;
    inject(DestroyRef).onDestroy(() => {
      destroyed = true;
      this.list?.destroy(); // a list stays registered until it is destroyed
    });

    this.dcuplService.instance().then(
      (dcupl) => {
        if (destroyed) return;
        this.list = dcupl.lists.create<Product>({ modelKey: 'Product' });
        // every filter change and every data update ends up here
        this.list.onResultChange(() => this.read());
        this.read();
        this.status.set('ready');
      },
      () => this.status.set('error'),
    );
  }

  /** Copies the list's current result into the signals the template reads. */
  private read(): void {
    if (!this.list) return;
    this.items.set(this.list.catalog.query.items());
    this.total.set(this.list.catalog.fn.metadata().currentSize);
    this.categories.set(
      this.list.catalog.fn
        .facets({ attribute: 'category', excludeZeros: false, skipKeys: true })
        .map(({ value, size, selected }) => ({ value: String(value), size, selected })),
    );
  }

  protected search(text: string): void {
    const query = this.list?.catalog.query;
    if (!query) return;
    const pattern = text.trim().replace(/[.*+?^${}()|[\]\\/]/g, '\\$&');
    if (pattern) {
      query.setCondition({ attribute: 'name', operator: 'find', value: `/${pattern}/`, options: { regexFlags: 'i' } });
    } else {
      query.removeGroup('name');
    }
  }

  protected toggleCategory(option: CategoryOption): void {
    const condition = { attribute: 'category', operator: 'eq' as const, value: option.value };
    if (option.selected) {
      this.list?.catalog.query.removeCondition(condition);
    } else {
      this.list?.catalog.query.addCondition(condition);
    }
  }
}
  • Search: setCondition() replaces the condition on name, so typing never stacks conditions; removeGroup('name') drops it when the field is empty. A find value between slashes is a regular expression, so the user's text is escaped first (find).
  • Categories: conditions on the same attribute are combined with OR, so two ticked categories show both. facets() leaves out the category conditions when it counts, so every option shows how many products it would add, and selected says whether it is ticked (Facets).
  • Zoneless: the onResultChange callback runs outside any Angular event. Writing to signals is what schedules the view update; a plain field would not update the page.

Step 5: the template and the app

src/app/catalog/catalog.html
@switch (status()) {
  @case ('loading') {
    <p>Loading products…</p>
  }
  @case ('error') {
    <p role="alert">The products could not be loaded.</p>
  }
  @case ('ready') {
    <input
      #searchBox
      type="search"
      placeholder="Search products"
      aria-label="Search products"
      (input)="search(searchBox.value)"
    />

    <fieldset>
      <legend>Category</legend>
      @for (option of categories(); track option.value) {
        <label>
          <input type="checkbox" [checked]="option.selected" (change)="toggleCategory(option)" />
          {{ option.value }} ({{ option.size }})
        </label>
      }
    </fieldset>

    <p>{{ total() }} products</p>
    <ul>
      @for (product of items(); track product.key) {
        <li>{{ product.name }}: {{ product.price.toFixed(2) }}</li>
      } @empty {
        <li>No product matches these filters.</li>
      }
    </ul>
  }
}
src/app/catalog/catalog.css
:host {
  display: block;
  max-width: 40rem;
  margin: 2rem auto;
  font-family: system-ui, sans-serif;
}

fieldset {
  display: flex;
  gap: 1rem;
  margin: 1rem 0;
}

Replace the root component so it shows the catalog, and delete src/app/app.html, src/app/app.css and src/app/app.spec.ts (the generated test checks the welcome page):

src/app/app.ts
import { Component } from '@angular/core';
import { Catalog } from './catalog/catalog';

@Component({
  selector: 'app-root',
  imports: [Catalog],
  template: '<app-catalog />',
})
export class App {}

Start the dev server and open http://localhost:4200/:

terminal
npm start

The page lists eight products. Tick Sports and it shows three; type wat and only the Water Bottle is left; untick Sports and the Smart Watch comes back.

Step 6: load from the Console instead

To load the models and data of a Console project, install the loader and replace load() in the service. The rest of the app stays as it is:

terminal
npm install @dcupl/loader@2
load() in src/app/dcupl/dcupl.service.ts
import { Dcupl } from '@dcupl/core';
import { DcuplAppLoader } from '@dcupl/loader';

// in DcuplService:
private async load(): Promise<Dcupl> {
  const dcupl = new Dcupl({
    config: {
      projectId: 'your-project-id',
      apiKey: 'your-read-only-api-key', // ships to the browser: a read-only key only
    },
  });
  const loader = new DcuplAppLoader();
  dcupl.loaders.add(loader);
  await loader.config.fetch();
  await loader.process({ applicationKey: 'default' });
  if (!(await dcupl.init())) throw new Error('dcupl.init() failed');
  return dcupl;
}

Set modelKey and the filtered attributes to a model of your project. The key is part of the browser bundle, so anyone using the app can read it; see What the API key protects. Load from the Console covers the loader options.

Where to go from here

  • The Angular starter (dcupl-ng-starter) is a full version of this app: it loads the Console's Product Catalog project, builds the filter bar from a list of filter definitions, pages the results and ships with Vitest specs. Its README lists the four places to point it at your own project.
  • Filters in the URL: the Next.js guide keeps the filters in the query string. In Angular, read them from ActivatedRoute.queryParamMap and write them with router.navigate([], { queryParams, queryParamsHandling: 'merge' }).
  • Updates: data you change with dcupl.data.* and await dcupl.update() reaches the component through onResultChange, see Real-time updates.