Skip to content
Tutorials Center
My learning

Topics

Lesson 53 of 74 ยท Tooling and Ecosystem

Angular Material and the CDK

Learn what Angular Material and the Component Dev Kit offer, how to add components and theme them, and how CDK drag-drop and virtual scroll work, with runnable logic stand-ins.

Building a good date picker, dialog, data table or drag-and-drop list from scratch takes weeks, and getting keyboard support and screen reader behavior right takes longer. The Angular team maintains two packages that do the hard parts for you. Angular Material is a set of ready-made, accessible UI components that follow Google's Material Design. The CDK (Component Dev Kit) is the unstyled foundation underneath: behavior, with no look attached.

This lesson shows how to add and use Material components, how theming works, and which CDK tools are worth knowing: overlays, drag and drop, virtual scrolling and accessibility helpers. You can use the CDK without Material, which is a good choice when your design system is your own.

Real versus stand-in. Material and CDK need the Angular compiler and npm packages, so every typescript, html, scss and bash block here is real code to read. The runnable examples are stand-ins for the logic inside the CDK (reordering and moving items, working out a drop position, choosing which rows a virtual list renders). They are not the CDK itself. Component and theming APIs change between major versions, so check the Material docs for the version you install.

Adding Material

Terminal
ng add @angular/material

The command installs the packages and asks for a theme and typography options. Then you import only the components you use, directly into a standalone component's imports array (Your First Component):

TypeScript
import { Component, signal } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';

@Component({
  selector: 'app-sign-up',
  imports: [MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule],
  template: `
    <mat-card>
      <mat-card-header><mat-card-title>Join us</mat-card-title></mat-card-header>
      <mat-card-content>
        <mat-form-field appearance="outline">
          <mat-label>Email</mat-label>
          <input matInput type="email" #email />
        </mat-form-field>
      </mat-card-content>
      <mat-card-actions>
        <button mat-flat-button (click)="sent.set(true)">Sign up</button>
      </mat-card-actions>
    </mat-card>
    @if (sent()) { <p>Thanks!</p> }
  `,
})
export class SignUpComponent {
  sent = signal(false);
}

Material components attach to native elements through attribute selectors such as mat-flat-button and matInput, so you keep real <button> and <input> elements with their built-in accessibility. Importing per component keeps bundles small, because only what you import is included. Material also integrates with reactive forms: mat-form-field shows labels, hints and error messages from the control's state.

Commonly used pieces include buttons, cards, form fields, select, checkbox, radio, slide toggle, datepicker, autocomplete, table with sorting and pagination, tabs, stepper, menu, dialog, snack bar, tooltip and progress indicators.

Dialogs and snack bars are opened from code with injectable services:

TypeScript
import { Component, inject } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { MatSnackBar } from '@angular/material/snack-bar';

@Component({ selector: 'app-delete', template: `<button (click)="ask()">Delete</button>` })
export class DeleteComponent {
  private dialog = inject(MatDialog);
  private snackBar = inject(MatSnackBar);

  ask(): void {
    const ref = this.dialog.open(ConfirmDialogComponent, { data: { name: 'Report.pdf' } });
    ref.afterClosed().subscribe(confirmed => {
      if (confirmed) this.snackBar.open('Deleted', 'Undo', { duration: 4000 });
    });
  }
}

MatDialog returns a reference with an afterClosed() observable, which emits the value the dialog passed when it closed. The dialog traps focus, restores it afterwards and closes on Escape, all built on the CDK.

Theming

Material 3 themes are driven by design tokens exposed as CSS custom properties, and you configure them from Sass. In current versions the setup is a mixin call in your global stylesheet:

SCSS
@use '@angular/material' as mat;

html {
  color-scheme: light dark;
  @include mat.theme((
    color: (
      primary: mat.$azure-palette,
      tertiary: mat.$blue-palette,
    ),
    typography: Roboto,
    density: 0,
  ));
}

The mixin generates tokens like --mat-sys-primary and --mat-sys-surface that components read. Because they are plain CSS variables, you can use them in your own styles, so your custom parts match the theme, and you can override them on a single element or section:

SCSS
.warning-banner {
  background: var(--mat-sys-error-container);
  color: var(--mat-sys-on-error-container);
}

color-scheme: light dark lets the theme follow the user's system setting. Older projects use mat.define-theme and mat.all-component-themes, and Angular Material 2-style themes (mat.define-light-theme) are older still. The theming API has changed between releases, so when you read examples, check which version they target. Avoid reaching into Material's internal CSS classes with ::ng-deep; override tokens instead (Styling Components and View Encapsulation).

The CDK without Material

The CDK is split into small entry points, each importable on its own:

Entry point What it gives you
@angular/cdk/overlay Floating panels positioned next to an element: menus, tooltips, popovers, dialogs
@angular/cdk/drag-drop Draggable items, sortable lists, moving between lists
@angular/cdk/scrolling Virtual scroll viewport that renders only visible rows
@angular/cdk/a11y Focus trap, live announcer, focus monitor, keyboard list navigation
@angular/cdk/portal Rendering a component or template somewhere else in the DOM
@angular/cdk/table, /tree, /stepper, /menu Unstyled behavior for data tables, trees, steppers and menus
flowchart TD
  CDK["CDK<br/>behavior, no styling"] --> MAT["Angular Material<br/>CDK + Material Design styling"]
  CDK --> OWN["Your own design system<br/>CDK + your styles"]
  MAT --> APP["Your app"]
  OWN --> APP

Material is the CDK plus a visual design. If you have your own brand, build on the CDK instead.

Drag and drop

A sortable list with the CDK needs very little code:

TypeScript
import { Component, signal } from '@angular/core';
import { CdkDrag, CdkDragDrop, CdkDropList, moveItemInArray } from '@angular/cdk/drag-drop';

@Component({
  selector: 'app-playlist',
  imports: [CdkDropList, CdkDrag],
  template: `
    <ul cdkDropList (cdkDropListDropped)="drop($event)">
      @for (song of songs(); track song) {
        <li cdkDrag>{{ song }}</li>
      }
    </ul>
  `,
})
export class PlaylistComponent {
  songs = signal(['Intro', 'Verse', 'Chorus', 'Bridge', 'Outro']);

  drop(event: CdkDragDrop<string[]>): void {
    this.songs.update(list => {
      const copy = [...list];
      moveItemInArray(copy, event.previousIndex, event.currentIndex);
      return copy;
    });
  }
}

cdkDropList marks the container, cdkDrag each item, and cdkDropListDropped fires with the old and new index. The CDK does not reorder your data: you do that in the handler. We copy the array before calling moveItemInArray, because that helper mutates in place and signals need a new array (State Management with Signals and Services). The two helpers worth understanding are moveItemInArray and transferArrayItem (for moving between lists). Here are stand-ins for them:

TypeScript moveItemInArray and transferArrayItem, re-created

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

When you drag, the CDK also has to decide where the item would land. It compares the pointer position with the item midpoints. The stand-in below does the same calculation, and then the second half of the example works out which rows a virtual scroll viewport would render.

Virtual scrolling

Rendering 50,000 rows creates 50,000 elements and the page crawls. cdk-virtual-scroll-viewport renders only the rows that are visible, plus a small buffer, and uses a spacer element to keep the scrollbar the right size:

HTML
<cdk-virtual-scroll-viewport itemSize="48" class="list">
  <div *cdkVirtualFor="let row of rows()" class="row">{{ row.name }}</div>
</cdk-virtual-scroll-viewport>
SCSS
.list { height: 400px; }

The viewport needs a fixed height, and itemSize is the row height in pixels for the default strategy. The arithmetic is simple, and it is the heart of the feature.

TypeScript Drop position and the virtual scroll window

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

With 50,000 rows, the viewport renders only a dozen or so, and the spacer is the full height (50,000 x 48 = 2,400,000 pixels) so the scrollbar behaves normally. That is the whole trick, and it is why a virtual list needs a known item height (or a strategy that estimates it) and why Ctrl+F in the browser cannot find text in rows that are not rendered.

Overlay and accessibility

The overlay package positions a floating panel next to an origin element, repositions it on scroll and resize, handles a backdrop and layers it above the page. Menus, selects, autocomplete lists and dialogs in Material all use it. You rarely need it directly; when you do (a custom popover), you create a ComponentPortal, attach it to an overlay with a positioning strategy and dispose of it when done. The a11y package gives you cdkTrapFocus, LiveAnnouncer and ListKeyManager, covered in Security and Accessibility.

Going further: handles, connected lists, Overlay and Portal

The basic sortable list above hides several options you will want soon. A drag handle limits dragging to one element, connected lists let items move between containers, and a preview and placeholder can be restyled:

HTML
<div class="board" cdkDropListGroup>
  <ul cdkDropList #todoList="cdkDropList" [cdkDropListData]="todo()"
      [cdkDropListConnectedTo]="[doneList]" (cdkDropListDropped)="drop($event)">
    @for (task of todo(); track task) {
      <li cdkDrag [cdkDragData]="task">
        <span cdkDragHandle aria-label="Drag handle">&#9776;</span>
        {{ task }}
        <div *cdkDragPlaceholder class="placeholder"></div>
      </li>
    }
  </ul>

  <ul cdkDropList #doneList="cdkDropList" [cdkDropListData]="done()"
      (cdkDropListDropped)="drop($event)">
    @for (task of done(); track task) {
      <li cdkDrag>{{ task }}</li>
    }
  </ul>
</div>
TypeScript
drop(event: CdkDragDrop<string[]>): void {
  if (event.previousContainer === event.container) {
    moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
  } else {
    transferArrayItem(
      event.previousContainer.data,
      event.container.data,
      event.previousIndex,
      event.currentIndex,
    );
  }
}

cdkDropListGroup connects every list inside it automatically, and cdkDropListConnectedTo connects lists one by one. The event.container.data and previousContainer.data values come from cdkDropListData. With plain arrays this mutates them in place; with signals, copy first as shown earlier. Drag-and-drop is pointer based, so offer a keyboard alternative (buttons that move an item up or down) for people who cannot use a mouse.

The Overlay and Portal packages are the other half. A portal is a description of content ("render this component or template") that can be attached to any outlet. An overlay is a floating layer in a container at the end of <body>, so it is never clipped by a parent with overflow: hidden. Together they build a custom popover:

TypeScript
import { Overlay, OverlayRef } from '@angular/cdk/overlay';
import { ComponentPortal } from '@angular/cdk/portal';
import { Component, ElementRef, inject, OnDestroy } from '@angular/core';

@Component({
  selector: 'app-help-tip',
  template: `<div class="tip" role="tooltip">Press Enter to save.</div>`,
})
export class HelpTip {}

@Component({
  selector: 'app-field',
  template: `<button type="button" (click)="toggle()">Help</button>`,
})
export class Field implements OnDestroy {
  private readonly overlay = inject(Overlay);
  private readonly origin = inject(ElementRef);
  private ref: OverlayRef | null = null;

  toggle(): void {
    if (this.ref) {
      this.close();
      return;
    }
    const positionStrategy = this.overlay
      .position()
      .flexibleConnectedTo(this.origin)
      .withPositions([
        { originX: 'center', originY: 'bottom', overlayX: 'center', overlayY: 'top' },
        { originX: 'center', originY: 'top', overlayX: 'center', overlayY: 'bottom' },
      ]);
    this.ref = this.overlay.create({
      positionStrategy,
      scrollStrategy: this.overlay.scrollStrategies.reposition(),
      hasBackdrop: true,
      backdropClass: 'cdk-overlay-transparent-backdrop',
    });
    this.ref.attach(new ComponentPortal(HelpTip));
    this.ref.backdropClick().subscribe(() => this.close());
  }

  private close(): void {
    this.ref?.dispose();
    this.ref = null;
  }

  ngOnDestroy(): void {
    this.close();
  }
}

Each entry in withPositions pairs a point on the origin with a point on the overlay. The first position that fits in the viewport wins, so the list is a priority order: below first, above as a fallback. Always dispose of the overlay (here on close and in ngOnDestroy), or the layer stays in the DOM. For a template instead of a component use TemplatePortal; to render into your own spot use cdkPortalOutlet.

The stand-in below re-creates the "first position that fits" rule with plain numbers.

TypeScript Choosing an overlay position: first one that fits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The last case shows why the real CDK also supports pushing the panel back into view: a tip that fits neither below nor above, or sticks out on the left, needs a fallback. In the real API that is withPush(true) and withViewportMargin() on the position strategy.

Other component libraries

Material is not the only option, and many teams pick a different kit because of their design system:

  • PrimeNG is a large suite (data tables with sorting, filtering and lazy paging, calendars, tree views, charts, menus) with its own theming system. It is a common choice for data-heavy business apps. Its table component can host custom form elements in cells, such as inputs and dropdowns bound to each row.
  • ng-bootstrap and ngx-bootstrap are Angular implementations of Bootstrap components (modals, dropdowns, tabs, datepickers, carousels) written without jQuery. They give you a Bootstrap look. A modal, for example, is opened from a service and passes data to the component shown inside it.
  • Tailwind-based kits such as Spartan UI build on the CDK's accessibility primitives and let you own the styles (Using Tailwind, Bootstrap and Sass).

When you compare libraries, check five things: whether they support standalone components and signals, how accessible the components are, bundle size when tree-shaken, how theming works, and how actively the project follows new Angular releases. Mixing two full kits in one app usually means two sets of styles and two overlay systems, so choose one for the main UI and add the CDK for gaps.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the relationship between Angular Material and the CDK?

    The CDK provides behavior such as overlays, focus management and drag-drop. Material adds Material Design styling and ready-made components on top.
  2. 2. Why do Material components use selectors like mat-flat-button on native elements?

    The directive enhances a native element, so keyboard and screen reader behavior of the browser's own control is kept.
  3. 3. In the CDK drop handler, why copy the array before calling moveItemInArray?

    moveItemInArray changes the array it is given. Updating a signal with the same array object is not detected, so you reorder a copy.
  4. 4. What does cdk-virtual-scroll-viewport render for a list of 50,000 items?

    It renders a small window of rows and changes it as you scroll, using a spacer element of the full height so scrolling feels normal.
  5. 5. How do you adjust Material colors in a current theme?

    Theming is token-based. The theme mixin generates CSS variables such as --mat-sys-primary that you can use or override.

Summary

  • Angular Material is an accessible component library built on the CDK; the CDK alone gives you unstyled behavior for your own design system.
  • ng add @angular/material sets it up, and you import only the components you use into standalone components.
  • Current themes are token-based: a Sass mixin generates CSS custom properties you can reuse and override, and theming APIs differ between versions.
  • CDK drag-drop emits indexes and you update your own data (on a copy, for signals); virtual scroll renders only a window of rows.
  • Overlay, portal and a11y tools underlie Material's menus, dialogs and focus handling.

Next: Project Structure and Best Practices.