code block

Displays code, terminal output and diffs with an optional header, line numbers and a copy button.

PreviousNext
src/app/chat/chat.service.ts import { HttpClient } from '@angular/common/http';import { inject, Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' })export class ChatService { private readonly http = inject(HttpClient); send(messages: ChatMessage[]) { return this.http.post('/api/chat', { messages }, { observe: 'events', reportProgress: true, responseType: 'text', }); }}
import { isPlatformBrowser } from '@angular/common';
import { ChangeDetectionStrategy, Component, inject, PLATFORM_ID, signal } from '@angular/core';

import { NgIcon, provideIcons } from '@ng-icons/core';
import { lucideDownload, lucideFileCode, lucideWrapText } from '@ng-icons/lucide';

import { ZardButtonComponent } from '@/shared/components/button/button.component';
import { injectHighlightedCode } from '@/shared/components/code-block/code-block.highlight';
import { ZardCodeBlockImports } from '@/shared/components/code-block/code-block.imports';

const CODE = `import { HttpClient } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class ChatService {
  private readonly http = inject(HttpClient);

  send(messages: ChatMessage[]) {
    return this.http.post('/api/chat', { messages }, {
      observe: 'events',
      reportProgress: true,
      responseType: 'text',
    });
  }
}`;

/** The lines that call the API, highlighted in the block. */
const HIGHLIGHTED = [8, 9, 10, 11, 12];

@Component({
  selector: 'z-demo-code-block-preview',
  imports: [NgIcon, ZardButtonComponent, ...ZardCodeBlockImports],
  template: `
    <z-code-block class="max-w-lg">
      <z-code-block-header>
        <z-code-block-title>
          <ng-icon name="lucideFileCode" />
          src/app/chat/chat.service.ts
        </z-code-block-title>
        <z-code-block-actions>
          <button
            type="button"
            z-button
            zType="ghost"
            zSize="icon-xs"
            aria-label="Wrap lines"
            class="aria-pressed:text-foreground"
            [attr.aria-pressed]="wrap()"
            (click)="wrap.set(!wrap())"
          >
            <ng-icon name="lucideWrapText" />
          </button>
          <button type="button" z-button zType="ghost" zSize="icon-xs" aria-label="Download" (click)="download()">
            <ng-icon name="lucideDownload" />
          </button>
          <z-code-block-copy-button [zValue]="code" />
        </z-code-block-actions>
      </z-code-block-header>
      <z-code-block-content zLineNumbers [zWrap]="wrap()">
        @for (line of lines(); track $index) {
          <z-code-block-line [zTokens]="line" [zType]="highlighted.includes($index) ? 'highlighted' : 'default'" />
        }
      </z-code-block-content>
    </z-code-block>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
  viewProviders: [provideIcons({ lucideDownload, lucideFileCode, lucideWrapText })],
  host: { class: 'contents' },
})
export class ZardDemoCodeBlockPreviewComponent {
  private readonly isBrowser = isPlatformBrowser(inject(PLATFORM_ID));

  protected readonly code = CODE;
  protected readonly highlighted = HIGHLIGHTED;
  protected readonly wrap = signal(false);
  protected readonly lines = injectHighlightedCode(CODE, 'typescript');

  protected download(): void {
    if (!this.isBrowser) {
      return;
    }

    const url = URL.createObjectURL(new Blob([CODE], { type: 'text/plain' }));
    const link = document.createElement('a');
    link.href = url;
    link.download = 'chat.service.ts';
    link.click();
    URL.revokeObjectURL(url);
  }
}
z-code-block displays code, terminal output, logs and diffs. It has a header with a title and actions, line numbers, wrapping, diff and highlighted lines, and a small size for tool output in a Trace.
Syntax highlighting is optional and lives in a separate file, code-block.highlight.ts, so a block that only shows plain output stays small.

Installation

Copy
npx zard-cli@latest add code-block

Usage

import { ZardCodeBlockImports } from '@/shared/components/code-block/code-block.imports';
Copy
<z-code-block>
  <z-code-block-header>
    <z-code-block-title>Terminal</z-code-block-title>
    <z-code-block-actions>
      <z-code-block-copy-button [zValue]="output" />
    </z-code-block-actions>
  </z-code-block-header>
  <z-code-block-content>{{ output }}</z-code-block-content>
</z-code-block>
Copy

Composition

Use the following composition to build a code-block:

z-code-block
├── z-code-block-header
│   ├── z-code-block-title
│   └── z-code-block-actions
│       └── z-code-block-copy-button
├── z-code-block-actions (floating, when there is no header)
├── z-code-block-content
│   └── z-code-block-line
└── z-code-block-footer
Copy
z-code-block-content takes a string or a list of z-code-block-line. Use lines when you need line types or highlighted tokens.

Features

  • It streams cheaply. A string renders as one text node, and while code streams the highlighter keeps the colors of the lines that did not change.
  • It copies cleanly. Line numbers and diff markers are left out of a selection, and blank lines survive the copy.
  • It reads left to right. The content is always dir="ltr". The header follows the page direction.
  • It highlights without WASM. highlightCode() uses Shiki's JavaScript engine, loads each language on first use and renders ANSI colors in terminal output. It also runs on the server, so prerendered pages ship highlighted.
  • It fits where code shows up. Use it in a message, a Trace line, Tabs, a Dialog or a typeset container.
  • It scrolls by keyboard. The content is focusable, and floating actions show on focus as well as on hover.

Basic

Project a string into z-code-block-content. It renders as one text node, so it stays cheap while output streams.
$ ng build Initial chunk files | Names | Raw size | Estimated transfer size main-HJ2K4QXZ.js | main | 208.31 kB | 56.24 kB styles-5INURTSO.css | styles | 14.07 kB | 3.18 kB | Initial total | 222.38 kB | 59.42 kB Application bundle generation complete. [4.218 seconds]
import { ChangeDetectionStrategy, Component } from '@angular/core';

import { ZardCodeBlockImports } from '@/shared/components/code-block/code-block.imports';

@Component({
  selector: 'z-demo-code-block-basic',
  imports: [ZardCodeBlockImports],
  template: `
    <z-code-block class="max-w-md">
      <z-code-block-content>{{ output }}</z-code-block-content>
    </z-code-block>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { class: 'contents' },
})
export class ZardDemoCodeBlockBasicComponent {
  protected readonly output = `$ ng build
Initial chunk files   | Names         |  Raw size | Estimated transfer size
main-HJ2K4QXZ.js      | main          | 208.31 kB |                56.24 kB
styles-5INURTSO.css   | styles        |  14.07 kB |                 3.18 kB

                      | Initial total | 222.38 kB |                59.42 kB

Application bundle generation complete. [4.218 seconds]`;
}

Actions

z-code-block-actions holds any number of buttons. For a wrap toggle, keep the state yourself and bind it to zWrap.
Terminal $ ng lint src/app/chat/message-list.component.ts 18:22 error Unsafe call of an `any` typed value. Add a type to messages before calling map @typescript-eslint/no-unsafe-call 42:7 warning Prefer signal inputs over @Input() decorators so the template reacts to changes @angular-eslint/prefer-signals ✖ 2 problems (1 error, 1 warning)
import { isPlatformBrowser } from '@angular/common';
import { ChangeDetectionStrategy, Component, inject, PLATFORM_ID, signal } from '@angular/core';

import { NgIcon, provideIcons } from '@ng-icons/core';
import { lucideDownload, lucideTerminal, lucideWrapText } from '@ng-icons/lucide';

import { ZardButtonComponent } from '@/shared/components/button/button.component';
import { ZardCodeBlockImports } from '@/shared/components/code-block/code-block.imports';

const OUTPUT = `$ ng lint
src/app/chat/message-list.component.ts
  18:22  error    Unsafe call of an \`any\` typed value. Add a type to messages before calling map  @typescript-eslint/no-unsafe-call
  42:7   warning  Prefer signal inputs over @Input() decorators so the template reacts to changes  @angular-eslint/prefer-signals

✖ 2 problems (1 error, 1 warning)`;

@Component({
  selector: 'z-demo-code-block-actions',
  imports: [NgIcon, ZardButtonComponent, ...ZardCodeBlockImports],
  template: `
    <z-code-block class="max-w-md">
      <z-code-block-header>
        <z-code-block-title>
          <ng-icon name="lucideTerminal" />
          Terminal
        </z-code-block-title>
        <z-code-block-actions>
          <button
            type="button"
            z-button
            zType="ghost"
            zSize="icon-xs"
            aria-label="Wrap lines"
            class="aria-pressed:text-foreground"
            [attr.aria-pressed]="wrap()"
            (click)="wrap.set(!wrap())"
          >
            <ng-icon name="lucideWrapText" />
          </button>
          <button type="button" z-button zType="ghost" zSize="icon-xs" aria-label="Download" (click)="download()">
            <ng-icon name="lucideDownload" />
          </button>
          <z-code-block-copy-button [zValue]="output" />
        </z-code-block-actions>
      </z-code-block-header>
      <z-code-block-content [zWrap]="wrap()">{{ output }}</z-code-block-content>
    </z-code-block>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
  viewProviders: [provideIcons({ lucideDownload, lucideTerminal, lucideWrapText })],
  host: { class: 'contents' },
})
export class ZardDemoCodeBlockActionsComponent {
  private readonly isBrowser = isPlatformBrowser(inject(PLATFORM_ID));

  protected readonly output = OUTPUT;
  protected readonly wrap = signal(true);

  protected download(): void {
    if (!this.isBrowser) {
      return;
    }

    const url = URL.createObjectURL(new Blob([OUTPUT], { type: 'text/plain' }));
    const link = document.createElement('a');
    link.href = url;
    link.download = 'lint.log';
    link.click();
    URL.revokeObjectURL(url);
  }
}
<z-code-block-actions>
  <button
    type="button"
    z-button
    zType="ghost"
    zSize="icon-xs"
    aria-label="Wrap lines"
    [attr.aria-pressed]="wrap()"
    (click)="wrap.set(!wrap())"
  >
    <ng-icon name="lucideWrapText" />
  </button>
  <z-code-block-copy-button [zValue]="output" />
</z-code-block-actions>
<z-code-block-content [zWrap]="wrap()">{{ output }}</z-code-block-content>
Copy

Floating Actions

Without a header, put z-code-block-actions directly inside z-code-block. The actions float at the top end and stay hidden until the block is hovered or focused. They always show on touch screens.
$ pnpm add @angular/cdk @ng-icons/core @ng-icons/lucide Progress: resolved 412, reused 403, downloaded 9, added 9, done dependencies: + @angular/cdk 21.0.2 + @ng-icons/core 32.2.0 + @ng-icons/lucide 32.2.0 Done in 2.8s using pnpm v10.18.0
import { ChangeDetectionStrategy, Component } from '@angular/core';

import { ZardCodeBlockImports } from '@/shared/components/code-block/code-block.imports';

@Component({
  selector: 'z-demo-code-block-floating-actions',
  imports: [ZardCodeBlockImports],
  template: `
    <z-code-block class="max-w-md">
      <z-code-block-actions>
        <z-code-block-copy-button [zValue]="output" />
      </z-code-block-actions>
      <z-code-block-content>{{ output }}</z-code-block-content>
    </z-code-block>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { class: 'contents' },
})
export class ZardDemoCodeBlockFloatingActionsComponent {
  protected readonly output = `$ pnpm add @angular/cdk @ng-icons/core @ng-icons/lucide
Progress: resolved 412, reused 403, downloaded 9, added 9, done
dependencies:
+ @angular/cdk 21.0.2
+ @ng-icons/core 32.2.0
+ @ng-icons/lucide 32.2.0
Done in 2.8s using pnpm v10.18.0`;
}

Line Numbers

Add zLineNumbers to z-code-block-content. A string is split into lines, and the numbers are not copied with a selection.
{ "name": "chat", "private": true, "scripts": { "start": "ng serve", "build": "ng build" }}
import { ChangeDetectionStrategy, Component } from '@angular/core';

import { ZardCodeBlockImports } from '@/shared/components/code-block/code-block.imports';

@Component({
  selector: 'z-demo-code-block-line-numbers',
  imports: [ZardCodeBlockImports],
  template: `
    <z-code-block class="max-w-md">
      <z-code-block-content zLineNumbers>{{ code }}</z-code-block-content>
    </z-code-block>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { class: 'contents' },
})
export class ZardDemoCodeBlockLineNumbersComponent {
  protected readonly code = `{
  "name": "chat",
  "private": true,
  "scripts": {
    "start": "ng serve",
    "build": "ng build"
  }
}`;
}

Start Line

Set [zStartLine] to number lines from a given line, for a snippet from the middle of a file. The gutter grows to fit the widest number.
src/app/dashboard/dashboard.component.ts if (!session) { return this.router.parseUrl('/login'); } const projects = await this.projects.findAll({ ownerId: session.user.id, orderBy: 'updatedAt', }); this.projectList.set(projects);}
import { ChangeDetectionStrategy, Component } from '@angular/core';

import { injectHighlightedCode } from '@/shared/components/code-block/code-block.highlight';
import { ZardCodeBlockImports } from '@/shared/components/code-block/code-block.imports';

const CODE = `  if (!session) {
    return this.router.parseUrl('/login');
  }

  const projects = await this.projects.findAll({
    ownerId: session.user.id,
    orderBy: 'updatedAt',
  });

  this.projectList.set(projects);
}`;

@Component({
  selector: 'z-demo-code-block-start-line',
  imports: [ZardCodeBlockImports],
  template: `
    <z-code-block class="max-w-md">
      <z-code-block-header>
        <z-code-block-title>src/app/dashboard/dashboard.component.ts</z-code-block-title>
      </z-code-block-header>
      <z-code-block-content zLineNumbers [zStartLine]="995">
        @for (line of lines(); track $index) {
          <z-code-block-line [zTokens]="line" />
        }
      </z-code-block-content>
    </z-code-block>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { class: 'contents' },
})
export class ZardDemoCodeBlockStartLineComponent {
  protected readonly lines = injectHighlightedCode(CODE, 'typescript');
}

Wrap

Long lines scroll by default. Add zWrap to wrap them, which suits tool output and error messages. To let the reader toggle it, see Actions.
NG0201: No provider found for `HttpClient`. Source: Standalone[ChatComponent]. Path: ChatService -> HttpClient. Add provideHttpClient() to the providers of your application config and try again.NG0201: No provider found for `HttpClient`. Source: Standalone[ChatComponent]. Path: ChatService -> HttpClient. Add provideHttpClient() to the providers of your application config and try again.
import { ChangeDetectionStrategy, Component } from '@angular/core';

import { ZardCodeBlockImports } from '@/shared/components/code-block/code-block.imports';

@Component({
  selector: 'z-demo-code-block-wrap',
  imports: [ZardCodeBlockImports],
  template: `
    <div class="flex w-full max-w-md flex-col gap-4">
      <z-code-block>
        <z-code-block-content>{{ output }}</z-code-block-content>
      </z-code-block>
      <z-code-block>
        <z-code-block-content zWrap>{{ output }}</z-code-block-content>
      </z-code-block>
    </div>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { class: 'contents' },
})
export class ZardDemoCodeBlockWrapComponent {
  protected readonly output =
    'NG0201: No provider found for `HttpClient`. Source: Standalone[ChatComponent]. Path: ChatService -> HttpClient. Add provideHttpClient() to the providers of your application config and try again.';
}

Highlighted Lines

Render each line as a z-code-block-line and set zType="highlighted" on the lines to call out.
export const appConfig: ApplicationConfig = { providers: [ provideZonelessChangeDetection(), provideHttpClient(withFetch()), provideRouter(routes), ],};
import { ChangeDetectionStrategy, Component } from '@angular/core';

import { ZardCodeBlockImports } from '@/shared/components/code-block/code-block.imports';

const CODE = `export const appConfig: ApplicationConfig = {
  providers: [
    provideZonelessChangeDetection(),
    provideHttpClient(withFetch()),
    provideRouter(routes),
  ],
};`;

@Component({
  selector: 'z-demo-code-block-highlighted-lines',
  imports: [ZardCodeBlockImports],
  template: `
    <z-code-block class="max-w-md">
      <z-code-block-content zLineNumbers>
        @for (line of lines; track $index) {
          <z-code-block-line [zTokens]="line" [zType]="highlighted.includes($index) ? 'highlighted' : 'default'" />
        }
      </z-code-block-content>
    </z-code-block>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { class: 'contents' },
})
export class ZardDemoCodeBlockHighlightedLinesComponent {
  // One token list per line: plain text, no highlighting.
  protected readonly lines = CODE.split('\n').map(line => (line ? [{ content: line }] : []));
  protected readonly highlighted = [2, 3];
}

Diff

Set zType to added or removed on a z-code-block-line. Each one adds a + or − marker.
src/app/greeting/greeting.component.ts@Component({ selector: 'app-greeting', template: '<p>Hello, {{ name() }}</p>', template: `<p class="text-muted-foreground text-sm"> Hello, {{ name() }}! </p>`,})
import { ChangeDetectionStrategy, Component } from '@angular/core';

import { ZardCodeBlockImports } from '@/shared/components/code-block/code-block.imports';
import type { ZardCodeBlockLineTypeVariants } from '@/shared/components/code-block/code-block.variants';

const PATCH = ` @Component({
   selector: 'app-greeting',
-  template: '<p>Hello, {{ name() }}</p>',
+  template: \`<p class="text-muted-foreground text-sm">
+    Hello, {{ name() }}!
+  </p>\`,
 })`;

function lineType(line: string): ZardCodeBlockLineTypeVariants {
  if (line.startsWith('+')) {
    return 'added';
  }

  if (line.startsWith('-')) {
    return 'removed';
  }

  return 'default';
}

@Component({
  selector: 'z-demo-code-block-diff',
  imports: [ZardCodeBlockImports],
  template: `
    <z-code-block class="max-w-md">
      <z-code-block-header>
        <z-code-block-title>src/app/greeting/greeting.component.ts</z-code-block-title>
        <z-code-block-actions>
          <z-code-block-copy-button [zValue]="patch" />
        </z-code-block-actions>
      </z-code-block-header>
      <z-code-block-content>
        @for (line of lines; track $index) {
          <z-code-block-line [zType]="line.type">{{ line.text }}</z-code-block-line>
        }
      </z-code-block-content>
    </z-code-block>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { class: 'contents' },
})
export class ZardDemoCodeBlockDiffComponent {
  protected readonly patch = PATCH;

  // The first character of a diff row is the marker (+, - or a space); the line component draws it instead.
  protected readonly lines = PATCH.split('\n').map(line => ({ type: lineType(line), text: line.slice(1) }));
}

Height

Cap the height with a max-h-* class on z-code-block-content. The content scrolls inside the block.
Logs[01] GET /api/chat 200 in 12ms [02] GET /api/chat 200 in 19ms [03] GET /api/chat 200 in 26ms [04] GET /api/chat 200 in 33ms [05] GET /api/chat 200 in 40ms [06] GET /api/chat 200 in 47ms [07] GET /api/chat 200 in 14ms [08] GET /api/chat 200 in 21ms [09] GET /api/chat 200 in 28ms [10] GET /api/chat 200 in 35ms [11] GET /api/chat 200 in 42ms [12] GET /api/chat 200 in 49ms [13] GET /api/chat 200 in 16ms [14] GET /api/chat 200 in 23ms [15] GET /api/chat 200 in 30ms [16] GET /api/chat 200 in 37ms [17] GET /api/chat 200 in 44ms [18] GET /api/chat 200 in 51ms [19] GET /api/chat 200 in 18ms [20] GET /api/chat 200 in 25ms [21] GET /api/chat 200 in 32ms [22] GET /api/chat 200 in 39ms [23] GET /api/chat 200 in 46ms [24] GET /api/chat 200 in 13ms [25] GET /api/chat 200 in 20ms [26] GET /api/chat 200 in 27ms [27] GET /api/chat 200 in 34ms [28] GET /api/chat 200 in 41ms [29] GET /api/chat 200 in 48ms [30] GET /api/chat 200 in 15ms [31] GET /api/chat 200 in 22ms [32] GET /api/chat 200 in 29ms [33] GET /api/chat 200 in 36ms [34] GET /api/chat 200 in 43ms [35] GET /api/chat 200 in 50ms [36] GET /api/chat 200 in 17ms [37] GET /api/chat 200 in 24ms [38] GET /api/chat 200 in 31ms [39] GET /api/chat 200 in 38ms [40] GET /api/chat 200 in 45ms
import { ChangeDetectionStrategy, Component } from '@angular/core';

import { ZardCodeBlockImports } from '@/shared/components/code-block/code-block.imports';

const LOGS = Array.from(
  { length: 40 },
  (_, index) => `[${String(index + 1).padStart(2, '0')}] GET /api/chat 200 in ${12 + ((index * 7) % 40)}ms`,
).join('\n');

@Component({
  selector: 'z-demo-code-block-height',
  imports: [ZardCodeBlockImports],
  template: `
    <z-code-block class="max-w-md">
      <z-code-block-header>
        <z-code-block-title>Logs</z-code-block-title>
        <z-code-block-actions>
          <z-code-block-copy-button [zValue]="logs" />
        </z-code-block-actions>
      </z-code-block-header>
      <z-code-block-content class="scroll-fade-y max-h-48">{{ logs }}</z-code-block-content>
    </z-code-block>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { class: 'contents' },
})
export class ZardDemoCodeBlockHeightComponent {
  protected readonly logs = LOGS;
}
z-code-block-content fades its edges with scroll-fade as it scrolls: left and right by default, top and bottom when it wraps. Add scroll-fade-y to a capped block that does not wrap.

Show More

z-code-block-footer is a slot below the content. For Show More, cap the content while it is collapsed and put a ghost xs button in the footer.
src/app/chat/chat.component.ts@Component({ selector: 'app-chat', imports: [FormsModule, ZardButtonComponent, ZardInputDirective], template: ` <div class="flex flex-col gap-4"> @for (message of chat.messages(); track message.id) { <p>{{ message.text }}</p> } <form (ngSubmit)="send()"> <input z-input name="draft" [(ngModel)]="draft" /> <button z-button [disabled]="chat.status() !== 'ready'">Send</button> </form> </div> `,})export class ChatComponent { protected readonly chat = inject(ChatService); protected draft = ''; protected send(): void { this.chat.send(this.draft); this.draft = ''; }}
import { ChangeDetectionStrategy, Component, computed, signal } from '@angular/core';

import { NgIcon, provideIcons } from '@ng-icons/core';
import { lucideChevronDown } from '@ng-icons/lucide';

import { ZardButtonComponent } from '@/shared/components/button/button.component';
import { injectHighlightedCode } from '@/shared/components/code-block/code-block.highlight';
import { ZardCodeBlockImports } from '@/shared/components/code-block/code-block.imports';

const CHAT_COMPONENT_CODE = `@Component({
  selector: 'app-chat',
  imports: [FormsModule, ZardButtonComponent, ZardInputDirective],
  template: \`
    <div class="flex flex-col gap-4">
      @for (message of chat.messages(); track message.id) {
        <p>{{ message.text }}</p>
      }
      <form (ngSubmit)="send()">
        <input z-input name="draft" [(ngModel)]="draft" />
        <button z-button [disabled]="chat.status() !== 'ready'">Send</button>
      </form>
    </div>
  \`,
})
export class ChatComponent {
  protected readonly chat = inject(ChatService);
  protected draft = '';

  protected send(): void {
    this.chat.send(this.draft);
    this.draft = '';
  }
}`;

@Component({
  selector: 'z-demo-code-block-show-more',
  imports: [NgIcon, ZardButtonComponent, ...ZardCodeBlockImports],
  template: `
    <z-code-block class="max-w-md">
      <z-code-block-header>
        <z-code-block-title>src/app/chat/chat.component.ts</z-code-block-title>
        <z-code-block-actions>
          <z-code-block-copy-button [zValue]="code" />
        </z-code-block-actions>
      </z-code-block-header>
      <z-code-block-content id="code-block-show-more" zLineNumbers [class]="cap()">
        @for (line of lines(); track $index) {
          <z-code-block-line [zTokens]="line" />
        }
      </z-code-block-content>
      <z-code-block-footer class="justify-center">
        <button
          type="button"
          z-button
          zType="ghost"
          zSize="xs"
          aria-controls="code-block-show-more"
          [attr.aria-expanded]="expanded()"
          (click)="expanded.set(!expanded())"
        >
          <ng-icon name="lucideChevronDown" class="transition-transform in-aria-expanded:rotate-180" />
          {{ expanded() ? 'Show less' : 'Show more' }}
        </button>
      </z-code-block-footer>
    </z-code-block>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
  viewProviders: [provideIcons({ lucideChevronDown })],
  host: { class: 'contents' },
})
export class ZardDemoCodeBlockShowMoreComponent {
  protected readonly code = CHAT_COMPONENT_CODE;
  protected readonly expanded = signal(false);
  protected readonly lines = injectHighlightedCode(CHAT_COMPONENT_CODE, 'angular-ts');

  protected readonly cap = computed(() => (this.expanded() ? '' : 'scroll-fade-y max-h-64 overflow-y-hidden'));
}
<!-- cap() is 'scroll-fade-y max-h-64 overflow-y-hidden' while collapsed. -->
<z-code-block-content id="chat-code" [class]="cap()">{{ code }}</z-code-block-content>
<z-code-block-footer class="justify-center">
  <button
    type="button"
    z-button
    zType="ghost"
    zSize="xs"
    aria-controls="chat-code"
    [attr.aria-expanded]="expanded()"
    (click)="expanded.set(!expanded())"
  >
    {{ expanded() ? 'Show less' : 'Show more' }}
  </button>
</z-code-block-footer>
Copy

Max Height

To keep a long block from taking over the page, raise the cap instead of removing it. The expanded content scrolls, and the edges fade as you scroll.
src/app/chat/chat.component.ts@Component({ selector: 'app-chat', imports: [FormsModule, ZardButtonComponent, ZardInputDirective], template: ` <div class="flex flex-col gap-4"> @for (message of chat.messages(); track message.id) { <p>{{ message.text }}</p> } <form (ngSubmit)="send()"> <input z-input name="draft" [(ngModel)]="draft" /> <button z-button [disabled]="chat.status() !== 'ready'">Send</button> </form> </div> `,})export class ChatComponent { protected readonly chat = inject(ChatService); protected draft = ''; protected send(): void { this.chat.send(this.draft); this.draft = ''; }}
import { ChangeDetectionStrategy, Component, computed, signal } from '@angular/core';

import { NgIcon, provideIcons } from '@ng-icons/core';
import { lucideChevronDown } from '@ng-icons/lucide';

import { ZardButtonComponent } from '@/shared/components/button/button.component';
import { injectHighlightedCode } from '@/shared/components/code-block/code-block.highlight';
import { ZardCodeBlockImports } from '@/shared/components/code-block/code-block.imports';

const CODE = `@Component({
  selector: 'app-chat',
  imports: [FormsModule, ZardButtonComponent, ZardInputDirective],
  template: \`
    <div class="flex flex-col gap-4">
      @for (message of chat.messages(); track message.id) {
        <p>{{ message.text }}</p>
      }
      <form (ngSubmit)="send()">
        <input z-input name="draft" [(ngModel)]="draft" />
        <button z-button [disabled]="chat.status() !== 'ready'">Send</button>
      </form>
    </div>
  \`,
})
export class ChatComponent {
  protected readonly chat = inject(ChatService);
  protected draft = '';

  protected send(): void {
    this.chat.send(this.draft);
    this.draft = '';
  }
}`;

@Component({
  selector: 'z-demo-code-block-show-more-scroll',
  imports: [NgIcon, ZardButtonComponent, ...ZardCodeBlockImports],
  template: `
    <z-code-block class="max-w-md">
      <z-code-block-header>
        <z-code-block-title>src/app/chat/chat.component.ts</z-code-block-title>
        <z-code-block-actions>
          <z-code-block-copy-button [zValue]="code" />
        </z-code-block-actions>
      </z-code-block-header>
      <z-code-block-content id="code-block-show-more-scroll" zLineNumbers [class]="cap()">
        @for (line of lines(); track $index) {
          <z-code-block-line [zTokens]="line" />
        }
      </z-code-block-content>
      <z-code-block-footer class="justify-center">
        <button
          type="button"
          z-button
          zType="ghost"
          zSize="xs"
          aria-controls="code-block-show-more-scroll"
          [attr.aria-expanded]="expanded()"
          (click)="expanded.set(!expanded())"
        >
          <ng-icon name="lucideChevronDown" class="transition-transform in-aria-expanded:rotate-180" />
          {{ expanded() ? 'Show less' : 'Show more' }}
        </button>
      </z-code-block-footer>
    </z-code-block>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
  viewProviders: [provideIcons({ lucideChevronDown })],
  host: { class: 'contents' },
})
export class ZardDemoCodeBlockShowMoreScrollComponent {
  protected readonly code = CODE;
  protected readonly expanded = signal(false);
  protected readonly lines = injectHighlightedCode(CODE, 'angular-ts');

  // Expanded, the cap is raised rather than removed, so a long block still scrolls inside the page.
  protected readonly cap = computed(() =>
    this.expanded() ? 'scroll-fade-y max-h-96' : 'scroll-fade-y max-h-64 overflow-y-hidden',
  );
}

Size

Use zSize="sm" for tool and Trace output. It has tighter padding and text-xs text.
Terminal $ pnpm add @angular/cdk @ng-icons/core @ng-icons/lucide Progress: resolved 412, reused 403, downloaded 9, added 9, done Done in 2.8s using pnpm v10.18.0 Terminal $ pnpm add @angular/cdk @ng-icons/core @ng-icons/lucide Progress: resolved 412, reused 403, downloaded 9, added 9, done Done in 2.8s using pnpm v10.18.0
import { ChangeDetectionStrategy, Component } from '@angular/core';

import { NgIcon, provideIcons } from '@ng-icons/core';
import { lucideTerminal } from '@ng-icons/lucide';

import { ZardCodeBlockImports } from '@/shared/components/code-block/code-block.imports';

@Component({
  selector: 'z-demo-code-block-size',
  imports: [NgIcon, ZardCodeBlockImports],
  template: `
    <div class="flex w-full max-w-md flex-col gap-4">
      @for (size of sizes; track size) {
        <z-code-block [zSize]="size">
          <z-code-block-header>
            <z-code-block-title>
              <ng-icon name="lucideTerminal" />
              Terminal
            </z-code-block-title>
            <z-code-block-actions>
              <z-code-block-copy-button [zValue]="output" />
            </z-code-block-actions>
          </z-code-block-header>
          <z-code-block-content zWrap>{{ output }}</z-code-block-content>
        </z-code-block>
      }
    </div>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
  viewProviders: [provideIcons({ lucideTerminal })],
  host: { class: 'contents' },
})
export class ZardDemoCodeBlockSizeComponent {
  protected readonly sizes = ['default', 'sm'] as const;

  protected readonly output = `$ pnpm add @angular/cdk @ng-icons/core @ng-icons/lucide
Progress: resolved 412, reused 403, downloaded 9, added 9, done
Done in 2.8s using pnpm v10.18.0`;
}

Destructive

Use zType="destructive" for errors and failed output.
ErrorERROR TypeError: Cannot read properties of undefined (reading 'map') at MessageListComponent_Template (message-list.component.html:4:22) at executeTemplate (core.mjs:12162:9)
import { ChangeDetectionStrategy, Component } from '@angular/core';

import { ZardCodeBlockImports } from '@/shared/components/code-block/code-block.imports';

@Component({
  selector: 'z-demo-code-block-destructive',
  imports: [ZardCodeBlockImports],
  template: `
    <z-code-block zType="destructive" class="max-w-md">
      <z-code-block-header>
        <z-code-block-title>Error</z-code-block-title>
        <z-code-block-actions>
          <z-code-block-copy-button [zValue]="error" />
        </z-code-block-actions>
      </z-code-block-header>
      <z-code-block-content zWrap>{{ error }}</z-code-block-content>
    </z-code-block>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { class: 'contents' },
})
export class ZardDemoCodeBlockDestructiveComponent {
  protected readonly error = `ERROR TypeError: Cannot read properties of undefined (reading 'map')
    at MessageListComponent_Template (message-list.component.html:4:22)
    at executeTemplate (core.mjs:12162:9)`;
}

Trace

Put a z-code-block with zSize="sm" in z-trace-collapsible-content for tool and terminal output. Add zWrap and a max-h-64 class to z-code-block-content so long output wraps and scrolls inside the trace. The block sets its own text color, so z-trace-collapsible-content does not mute it.
$ node --version v24.18.0
$ ng serve Port 4200 is already in use. Would you like to use a different port? Use '--port' to specify one.
import { ChangeDetectionStrategy, Component } from '@angular/core';

import { NgIcon, provideIcons } from '@ng-icons/core';
import { lucideTerminal } from '@ng-icons/lucide';

import { ZardCodeBlockImports } from '@/shared/components/code-block/code-block.imports';
import { ZardTraceImports } from '@/shared/components/trace/trace.imports';

@Component({
  selector: 'z-demo-code-block-trace',
  imports: [NgIcon, ...ZardCodeBlockImports, ...ZardTraceImports],
  template: `
    <z-trace class="max-w-md">
      <z-trace-collapsible zOpen>
        <z-trace-collapsible-trigger>
          <z-trace-line>
            <z-trace-icon><ng-icon name="lucideTerminal" /></z-trace-icon>
            <z-trace-title>Ran node --version</z-trace-title>
          </z-trace-line>
        </z-trace-collapsible-trigger>
        <z-trace-collapsible-content>
          <z-code-block zSize="sm">
            <z-code-block-content zWrap class="max-h-64">{{ output }}</z-code-block-content>
          </z-code-block>
        </z-trace-collapsible-content>
      </z-trace-collapsible>

      <z-trace-collapsible zOpen>
        <z-trace-collapsible-trigger>
          <z-trace-line zStatus="error">
            <z-trace-icon><ng-icon name="lucideTerminal" /></z-trace-icon>
            <z-trace-title>Failed to run ng serve</z-trace-title>
          </z-trace-line>
        </z-trace-collapsible-trigger>
        <z-trace-collapsible-content>
          <z-code-block zSize="sm" zType="destructive">
            <z-code-block-content zWrap class="max-h-64">{{ error }}</z-code-block-content>
          </z-code-block>
        </z-trace-collapsible-content>
      </z-trace-collapsible>
    </z-trace>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
  viewProviders: [provideIcons({ lucideTerminal })],
  host: { class: 'contents' },
})
export class ZardDemoCodeBlockTraceComponent {
  protected readonly output = `$ node --version
v24.18.0`;

  protected readonly error = `$ ng serve
Port 4200 is already in use.
Would you like to use a different port? Use '--port' to specify one.`;
}

Tabs

Show several files with Tabs, one z-code-block in each z-tab.
src/app/chat/chat.service.ts@Injectable({ providedIn: 'root' })export class ChatService { private readonly http = inject(HttpClient); send(messages: ChatMessage[]) { return this.http.post('/api/chat', { messages }, { responseType: 'text' }); }}
import { ChangeDetectionStrategy, Component } from '@angular/core';

import { injectHighlightedCode } from '@/shared/components/code-block/code-block.highlight';
import { ZardCodeBlockImports } from '@/shared/components/code-block/code-block.imports';
import { ZardTabComponent, ZardTabGroupComponent } from '@/shared/components/tabs/tabs.component';

const FILES = [
  {
    title: 'src/app/chat/chat.service.ts',
    language: 'typescript',
    code: `@Injectable({ providedIn: 'root' })
export class ChatService {
  private readonly http = inject(HttpClient);

  send(messages: ChatMessage[]) {
    return this.http.post('/api/chat', { messages }, { responseType: 'text' });
  }
}`,
  },
  {
    title: 'src/app/chat/chat.component.ts',
    language: 'angular-ts',
    code: `@Component({
  selector: 'app-chat',
  template: \`<app-message-list [messages]="chat.messages()" />\`,
})
export class ChatComponent {
  protected readonly chat = inject(ChatService);
}`,
  },
  {
    title: 'proxy.conf.json',
    language: 'json',
    code: `{
  "/api": { "target": "http://localhost:3000", "secure": false }
}`,
  },
];

@Component({
  selector: 'z-demo-code-block-tabs',
  imports: [ZardTabComponent, ZardTabGroupComponent, ...ZardCodeBlockImports],
  template: `
    <z-tab-group class="w-full max-w-md">
      @for (file of files; track file.title) {
        <z-tab [label]="file.title.split('/').at(-1)!">
          <z-code-block>
            <z-code-block-header>
              <z-code-block-title>{{ file.title }}</z-code-block-title>
              <z-code-block-actions>
                <z-code-block-copy-button [zValue]="file.code" />
              </z-code-block-actions>
            </z-code-block-header>
            <z-code-block-content zLineNumbers>
              @for (line of file.lines(); track $index) {
                <z-code-block-line [zTokens]="line" />
              }
            </z-code-block-content>
          </z-code-block>
        </z-tab>
      }
    </z-tab-group>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { class: 'contents' },
})
export class ZardDemoCodeBlockTabsComponent {
  protected readonly files = FILES.map(file => ({ ...file, lines: injectHighlightedCode(file.code, file.language) }));
}

Message

Put a z-code-block between paragraphs inside a Message.
How do I stream a response?

Create a service that asks for the progress events:

src/app/chat/chat.service.ts@Injectable({ providedIn: 'root' })export class ChatService { private readonly http = inject(HttpClient); stream(messages: ChatMessage[]) { return this.http.post('/api/chat', { messages }, { observe: 'events', reportProgress: true, responseType: 'text', }); }}

The component reads the partial text from each event.

import { ChangeDetectionStrategy, Component } from '@angular/core';

import { ZardBubbleImports } from '@/shared/components/bubble/bubble.imports';
import { injectHighlightedCode } from '@/shared/components/code-block/code-block.highlight';
import { ZardCodeBlockImports } from '@/shared/components/code-block/code-block.imports';
import { ZardMessageImports } from '@/shared/components/message/message.imports';

const CODE = `@Injectable({ providedIn: 'root' })
export class ChatService {
  private readonly http = inject(HttpClient);

  stream(messages: ChatMessage[]) {
    return this.http.post('/api/chat', { messages }, {
      observe: 'events',
      reportProgress: true,
      responseType: 'text',
    });
  }
}`;

@Component({
  selector: 'z-demo-code-block-message',
  imports: [...ZardBubbleImports, ...ZardCodeBlockImports, ...ZardMessageImports],
  template: `
    <div class="flex w-full max-w-md flex-col gap-4 text-sm">
      <z-message zAlign="end">
        <z-message-content>
          <z-bubble zAlign="end" zVariant="muted">
            <z-bubble-content>How do I stream a response?</z-bubble-content>
          </z-bubble>
        </z-message-content>
      </z-message>
      <z-message>
        <z-message-content class="gap-3">
          <p>Create a service that asks for the progress events:</p>
          <z-code-block>
            <z-code-block-header>
              <z-code-block-title>src/app/chat/chat.service.ts</z-code-block-title>
              <z-code-block-actions>
                <z-code-block-copy-button [zValue]="code" />
              </z-code-block-actions>
            </z-code-block-header>
            <z-code-block-content>
              @for (line of lines(); track $index) {
                <z-code-block-line [zTokens]="line" />
              }
            </z-code-block-content>
          </z-code-block>
          <p>The component reads the partial text from each event.</p>
        </z-message-content>
      </z-message>
    </div>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { class: 'contents' },
})
export class ZardDemoCodeBlockMessageComponent {
  protected readonly code = CODE;
  protected readonly lines = injectHighlightedCode(CODE, 'typescript');
}

Typeset

A z-code-block inside a typeset container keeps its own styles and gets the same space above as a paragraph.

Stream a response

Create a service that posts the messages with HttpClient and returns the response to the component.

src/app/chat/chat.service.ts @Injectable({ providedIn: 'root' })export class ChatService { private readonly http = inject(HttpClient); send(messages: ChatMessage[]) { return this.http.post('/api/chat', { messages }, { responseType: 'text' }); }}

The component turns the response into a signal with toSignal and renders the answer while it is written.

import { ChangeDetectionStrategy, Component } from '@angular/core';

import { NgIcon, provideIcons } from '@ng-icons/core';
import { lucideFileCode } from '@ng-icons/lucide';

import { injectHighlightedCode } from '@/shared/components/code-block/code-block.highlight';
import { ZardCodeBlockImports } from '@/shared/components/code-block/code-block.imports';

const CODE = `@Injectable({ providedIn: 'root' })
export class ChatService {
  private readonly http = inject(HttpClient);

  send(messages: ChatMessage[]) {
    return this.http.post('/api/chat', { messages }, { responseType: 'text' });
  }
}`;

@Component({
  selector: 'z-demo-code-block-typeset',
  imports: [NgIcon, ...ZardCodeBlockImports],
  template: `
    <div class="typeset w-full max-w-md">
      <h3>Stream a response</h3>
      <p>
        Create a service that posts the messages with
        <code>HttpClient</code>
        and returns the response to the component.
      </p>
      <z-code-block>
        <z-code-block-header>
          <z-code-block-title>
            <ng-icon name="lucideFileCode" />
            src/app/chat/chat.service.ts
          </z-code-block-title>
          <z-code-block-actions>
            <z-code-block-copy-button [zValue]="code" />
          </z-code-block-actions>
        </z-code-block-header>
        <z-code-block-content zLineNumbers>
          @for (line of lines(); track $index) {
            <z-code-block-line [zTokens]="line" />
          }
        </z-code-block-content>
      </z-code-block>
      <p>
        The component turns the response into a signal with
        <code>toSignal</code>
        and renders the answer while it is written.
      </p>
    </div>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
  viewProviders: [provideIcons({ lucideFileCode })],
  host: { class: 'contents' },
})
export class ZardDemoCodeBlockTypesetComponent {
  protected readonly code = CODE;
  protected readonly lines = injectHighlightedCode(CODE, 'typescript');
}

RTL

To enable RTL support in zard/ui, see the RTL configuration guide. Code always reads left to right. The header follows the page direction.

ثبّت الحزم، ثم شغّل خادم التطوير.

الطرفية pnpm add @angular/cdk @ng-icons/core @ng-icons/lucideng serve
// You will notice this example is rendered inside a wrapper that sets the dir and data-lang attributes, and
// reads its text from a translations helper. This is because this site is not RTL by default.
// In your application you won't need either: set dir="rtl" on <html> (or use the CDK Dir directive on a subtree)
// and write the text of your own language. See the RTL guide: https://zardui.com/docs/rtl

import { ChangeDetectionStrategy, Component } from '@angular/core';

import { NgIcon, provideIcons } from '@ng-icons/core';
import { lucideTerminal } from '@ng-icons/lucide';

import { injectHighlightedCode } from '@/shared/components/code-block/code-block.highlight';
import { ZardCodeBlockImports } from '@/shared/components/code-block/code-block.imports';
import { injectRtlTranslation, type ZardRtlTranslations } from '@/shared/demo-utils/rtl-translation';

interface CodeBlockRtlValues {
  description: string;
  title: string;
}

const translations: ZardRtlTranslations<CodeBlockRtlValues> = {
  en: {
    dir: 'ltr',
    values: { description: 'Install the packages, then start the dev server.', title: 'Terminal' },
  },
  ar: {
    dir: 'rtl',
    values: { description: 'ثبّت الحزم، ثم شغّل خادم التطوير.', title: 'الطرفية' },
  },
  he: {
    dir: 'rtl',
    values: { description: 'התקן את החבילות, ואז הפעל את שרת הפיתוח.', title: 'מסוף' },
  },
};

const CODE = `pnpm add @angular/cdk @ng-icons/core @ng-icons/lucide
ng serve`;

@Component({
  selector: 'z-demo-code-block-rtl',
  imports: [NgIcon, ZardCodeBlockImports],
  template: `
    <div class="flex w-full max-w-md flex-col gap-3 text-sm">
      <p>{{ i18n.t().description }}</p>
      <z-code-block>
        <z-code-block-header>
          <z-code-block-title>
            <ng-icon name="lucideTerminal" />
            {{ i18n.t().title }}
          </z-code-block-title>
          <z-code-block-actions>
            <z-code-block-copy-button [zValue]="code" />
          </z-code-block-actions>
        </z-code-block-header>
        <!-- Code always reads left to right: only the header follows the page direction. -->
        <z-code-block-content zLineNumbers>
          @for (line of lines(); track $index) {
            <z-code-block-line [zTokens]="line" />
          }
        </z-code-block-content>
      </z-code-block>
    </div>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
  viewProviders: [provideIcons({ lucideTerminal })],
  host: { class: 'contents' },
})
export class ZardDemoCodeBlockRtlComponent {
  protected readonly i18n = injectRtlTranslation(translations);
  protected readonly code = CODE;
  protected readonly lines = injectHighlightedCode(CODE, 'bash');
}

Syntax Highlighting

injectHighlightedCode() highlights with Shiki and returns a signal with one list of tokens per line, for [zTokens] on z-code-block-line.
getWeather output{ "location": "San Francisco", "temperature": 18, "unit": "celsius", "conditions": ["fog", "wind"]}
import { ChangeDetectionStrategy, Component } from '@angular/core';

import { injectHighlightedCode } from '@/shared/components/code-block/code-block.highlight';
import { ZardCodeBlockImports } from '@/shared/components/code-block/code-block.imports';

const CODE = `{
  "location": "San Francisco",
  "temperature": 18,
  "unit": "celsius",
  "conditions": ["fog", "wind"]
}`;

@Component({
  selector: 'z-demo-code-block-highlighting',
  imports: [ZardCodeBlockImports],
  template: `
    <z-code-block class="max-w-md">
      <z-code-block-header>
        <z-code-block-title>getWeather output</z-code-block-title>
      </z-code-block-header>
      <z-code-block-content>
        @for (line of lines(); track $index) {
          <z-code-block-line [zTokens]="line" />
        }
      </z-code-block-content>
    </z-code-block>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { class: 'contents' },
})
export class ZardDemoCodeBlockHighlightingComponent {
  protected readonly lines = injectHighlightedCode(CODE, 'json');
}
import { injectHighlightedCode } from '@/shared/components/code-block/code-block.highlight';

export class WeatherOutputComponent {
  // Plain lines until Shiki has run, then the highlighted ones.
  protected readonly lines = injectHighlightedCode(this.code, 'json');
}
Copy
<z-code-block>
  <z-code-block-content>
    @for (line of lines(); track $index) {
      <z-code-block-line [zTokens]="line" />
    }
  </z-code-block-content>
</z-code-block>
Copy
Shiki uses its JavaScript regex engine, so there is no WASM to load.

Languages

Each language loads the first time it is used. Edit the list in code-block.highlight.ts. A language that is not in the list renders as plain text.
src/styles.css@import "tailwindcss"; :root { --radius: 0.625rem;}src/app/app.html@if (user(); as user) { <p>Hello, {{ user.name }}!</p>}notes.txtA language that is not in the list renders as plain text.
import { ChangeDetectionStrategy, Component } from '@angular/core';

import { injectHighlightedCode } from '@/shared/components/code-block/code-block.highlight';
import { ZardCodeBlockImports } from '@/shared/components/code-block/code-block.imports';

const SAMPLES = [
  {
    language: 'css',
    title: 'src/styles.css',
    code: `@import "tailwindcss";

:root {
  --radius: 0.625rem;
}`,
  },
  {
    language: 'angular-html',
    title: 'src/app/app.html',
    code: `@if (user(); as user) {
  <p>Hello, {{ user.name }}!</p>
}`,
  },
  {
    language: 'text',
    title: 'notes.txt',
    code: 'A language that is not in the list renders as plain text.',
  },
];

@Component({
  selector: 'z-demo-code-block-languages',
  imports: [ZardCodeBlockImports],
  template: `
    <div class="flex w-full max-w-md flex-col gap-4">
      @for (sample of samples; track sample.language) {
        <z-code-block>
          <z-code-block-header>
            <z-code-block-title>{{ sample.title }}</z-code-block-title>
          </z-code-block-header>
          <z-code-block-content>
            @for (line of sample.lines(); track $index) {
              <z-code-block-line [zTokens]="line" />
            }
          </z-code-block-content>
        </z-code-block>
      }
    </div>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { class: 'contents' },
})
export class ZardDemoCodeBlockLanguagesComponent {
  protected readonly samples = SAMPLES.map(sample => ({
    ...sample,
    lines: injectHighlightedCode(sample.code, sample.language),
  }));
}
The list ships with angular-html, angular-ts, bash, css, diff, html, javascript, json, jsx, markdown, python, scss, sql, tsx, typescript and yaml, plus aliases such as ts, js, sh and yml.

Terminal Output

Pass ansi as the language to render the colors in terminal output. Without it, escape codes show as text.
Terminal $ ng test✓ src/app/format.spec.ts (4 tests)✓ src/app/parse.spec.ts (7 tests)✗ src/app/chat/chat.service.spec.ts (3 tests | 1 failed) AssertionError: expected 'hello' to be 'hello world' Tests 1 failed | 13 passed (14)
import { ChangeDetectionStrategy, Component } from '@angular/core';

import { NgIcon, provideIcons } from '@ng-icons/core';
import { lucideTerminal } from '@ng-icons/lucide';

import { injectHighlightedCode } from '@/shared/components/code-block/code-block.highlight';
import { ZardCodeBlockImports } from '@/shared/components/code-block/code-block.imports';

const ESC = String.fromCharCode(27);

const OUTPUT = [
  '$ ng test',
  `${ESC}[32m✓${ESC}[39m src/app/format.spec.ts ${ESC}[2m(4 tests)${ESC}[22m`,
  `${ESC}[32m✓${ESC}[39m src/app/parse.spec.ts ${ESC}[2m(7 tests)${ESC}[22m`,
  `${ESC}[31m✗${ESC}[39m src/app/chat/chat.service.spec.ts ${ESC}[2m(3 tests | 1 failed)${ESC}[22m`,
  '',
  `${ESC}[31mAssertionError: expected 'hello' to be 'hello world'${ESC}[39m`,
  '',
  `Tests  ${ESC}[31m1 failed${ESC}[39m | ${ESC}[32m13 passed${ESC}[39m (14)`,
].join('\n');

// The text to copy has no escape codes.
const PLAIN_OUTPUT = OUTPUT.replace(new RegExp(`${ESC}\\[[0-9;]*m`, 'g'), '');

@Component({
  selector: 'z-demo-code-block-terminal',
  imports: [NgIcon, ZardCodeBlockImports],
  template: `
    <z-code-block class="max-w-md">
      <z-code-block-header>
        <z-code-block-title>
          <ng-icon name="lucideTerminal" />
          Terminal
        </z-code-block-title>
        <z-code-block-actions>
          <z-code-block-copy-button [zValue]="plainOutput" />
        </z-code-block-actions>
      </z-code-block-header>
      <z-code-block-content zWrap>
        @for (line of lines(); track $index) {
          <z-code-block-line [zTokens]="line" />
        }
      </z-code-block-content>
    </z-code-block>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
  viewProviders: [provideIcons({ lucideTerminal })],
  host: { class: 'contents' },
})
export class ZardDemoCodeBlockTerminalComponent {
  protected readonly plainOutput = PLAIN_OUTPUT;
  protected readonly lines = injectHighlightedCode(OUTPUT, 'ansi');
}
ANSI colors do not carry from one line to the next.

Server Rendering

highlightCode() is async and has no DOM dependency, so it runs during server rendering and prerendering. A resource holds the render until the lines are ready, so the HTML ships already highlighted.
import { Component, input, resource } from '@angular/core';

import { highlightCode } from '@/shared/components/code-block/code-block.highlight';

@Component({
  selector: 'app-server-code',
  imports: [ZardCodeBlockImports],
  template: `
    <z-code-block>
      <z-code-block-content zLineNumbers>
        @for (line of highlighted.value() ?? []; track $index) {
          <z-code-block-line [zTokens]="line" />
        }
      </z-code-block-content>
    </z-code-block>
  `,
})
export class ServerCodeComponent {
  readonly code = input.required<string>();

  // A resource holds the server render until the lines are highlighted, so the HTML ships with its colors.
  protected readonly highlighted = resource({
    params: () => this.code(),
    loader: ({ params }) => highlightCode(params, 'typescript'),
  });
}
Copy

Streaming

While the code streams, injectHighlightedCode() highlights it again, and every line that did not change keeps its colors, so the block does not flicker as it grows. Disable the copy button with zDisabled until the code is complete.
src/app/shared/debounced.tsexport function debounced<T>(source: Signal<T>, delay = 300): Signal<T> { const value = signal(source()); effect(onCleanup => { const next = source(); const timeout = setTimeout(() => value.set(next), delay); onCleanup(() => clearTimeout(timeout)); }); return value.asReadonly();}npx zard-cli@latest add code-blocksrc/app/search/search.component.tsexport class SearchComponent { protected readonly query = signal(''); protected readonly results = injectSearch(this.query); protected readonly debouncedQuery = debounced(this.query, 300); protected readonly results = injectSearch(this.debouncedQuery);}src/app/chat/chat.service.ts@Injectable({ providedIn: 'root' })export class ChatService { private readonly http = inject(HttpClient); stream(messages: ChatMessage[]) { return this.http.post('/api/chat', { messages }, { observe: 'events', reportProgress: true, }); }}proxy.conf.json{ "/api": { "target": "http://localhost:3000" } }
import { ChangeDetectionStrategy, Component, computed, DestroyRef, inject, signal } from '@angular/core';

import { NgIcon, provideIcons } from '@ng-icons/core';
import { lucideRotateCcw } from '@ng-icons/lucide';

import { ZardButtonComponent } from '@/shared/components/button/button.component';
import { injectHighlightedCode } from '@/shared/components/code-block/code-block.highlight';
import { ZardCodeBlockImports } from '@/shared/components/code-block/code-block.imports';
import type { ZardCodeBlockLineTypeVariants } from '@/shared/components/code-block/code-block.variants';

interface StreamedBlock {
  readonly title?: string;
  readonly language: string;
  readonly code: string;
  readonly lineNumbers?: boolean;
  readonly highlight?: readonly number[];
  /** Rows start with `+`, `-` or a space; the marker is not part of the code. */
  readonly diff?: boolean;
}

const BLOCKS: readonly StreamedBlock[] = [
  {
    title: 'src/app/shared/debounced.ts',
    language: 'typescript',
    lineNumbers: true,
    code: `export function debounced<T>(source: Signal<T>, delay = 300): Signal<T> {
  const value = signal(source());

  effect(onCleanup => {
    const next = source();
    const timeout = setTimeout(() => value.set(next), delay);
    onCleanup(() => clearTimeout(timeout));
  });

  return value.asReadonly();
}`,
  },
  {
    language: 'bash',
    code: 'npx zard-cli@latest add code-block',
  },
  {
    title: 'src/app/search/search.component.ts',
    language: 'typescript',
    lineNumbers: true,
    diff: true,
    code: ` export class SearchComponent {
   protected readonly query = signal('');
-  protected readonly results = injectSearch(this.query);
+  protected readonly debouncedQuery = debounced(this.query, 300);
+  protected readonly results = injectSearch(this.debouncedQuery);
 }`,
  },
  {
    title: 'src/app/chat/chat.service.ts',
    language: 'typescript',
    lineNumbers: true,
    highlight: [4, 5, 6, 7, 8],
    code: `@Injectable({ providedIn: 'root' })
export class ChatService {
  private readonly http = inject(HttpClient);

  stream(messages: ChatMessage[]) {
    return this.http.post('/api/chat', { messages }, {
      observe: 'events',
      reportProgress: true,
    });
  }
}`,
  },
  {
    title: 'proxy.conf.json',
    language: 'json',
    code: `{ "/api": { "target": "http://localhost:3000" } }`,
  },
];

/** Where each block starts in the stream. */
const OFFSETS = BLOCKS.map((_, index) => BLOCKS.slice(0, index).reduce((total, block) => total + block.code.length, 0));
const TOTAL = BLOCKS.reduce((sum, block) => sum + block.code.length, 0);

@Component({
  selector: 'z-demo-code-block-streaming',
  imports: [NgIcon, ZardButtonComponent, ...ZardCodeBlockImports],
  template: `
    <div class="flex w-full max-w-md flex-col gap-4">
      @for (block of blocks; track $index) {
        @if (block.visible()) {
          <z-code-block>
            @if (block.title) {
              <z-code-block-header>
                <z-code-block-title>{{ block.title }}</z-code-block-title>
                <z-code-block-actions>
                  <!-- Copying is disabled until the block has arrived in full. -->
                  <z-code-block-copy-button [zValue]="block.source()" [zDisabled]="!block.complete()" />
                </z-code-block-actions>
              </z-code-block-header>
            }
            <z-code-block-content [zLineNumbers]="block.lineNumbers ?? false">
              @for (line of block.lines(); track $index) {
                <z-code-block-line [zTokens]="line" [zType]="block.lineType($index)" />
              }
            </z-code-block-content>
          </z-code-block>
        }
      }
      <button
        type="button"
        z-button
        zType="outline"
        zSize="sm"
        class="self-start"
        [zDisabled]="length() < total"
        (click)="replay()"
      >
        <ng-icon name="lucideRotateCcw" />
        Replay
      </button>
    </div>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
  viewProviders: [provideIcons({ lucideRotateCcw })],
  host: { class: 'contents' },
})
export class ZardDemoCodeBlockStreamingComponent {
  protected readonly total = TOTAL;
  /** How many characters of the whole stream have arrived. The page opens on the finished blocks. */
  protected readonly length = signal(TOTAL);

  protected readonly blocks = BLOCKS.map((block, index) => {
    const code = computed(() => block.code.slice(0, Math.max(0, this.length() - OFFSETS[index])));
    const rows = computed(() => code().split('\n'));
    const source = computed(() =>
      block.diff
        ? rows()
            .map(row => row.slice(1))
            .join('\n')
        : code(),
    );

    return {
      ...block,
      visible: computed(() => this.length() > OFFSETS[index]),
      complete: computed(() => code().length === block.code.length),
      source,
      // Highlighted again as the code grows; the lines that did not change keep their colors.
      lines: injectHighlightedCode(source, block.language),
      lineType: (line: number): ZardCodeBlockLineTypeVariants => {
        if (block.diff) {
          const row = rows()[line] ?? '';
          return row.startsWith('+') ? 'added' : row.startsWith('-') ? 'removed' : 'default';
        }
        return block.highlight?.includes(line) ? 'highlighted' : 'default';
      },
    };
  });

  private timer: ReturnType<typeof setTimeout> | undefined;

  constructor() {
    inject(DestroyRef).onDestroy(() => clearTimeout(this.timer));
  }

  protected replay(): void {
    this.length.set(0);
    this.tick();
  }

  private tick(): void {
    if (this.length() >= TOTAL) {
      return;
    }

    this.timer = setTimeout(() => {
      this.length.update(length => Math.min(TOTAL, length + 3));
      this.tick();
    }, 16);
  }
}

Accessibility

  • z-code-block-content holds a code element and always sets dir="ltr", so code reads left to right on an RTL page.
  • z-code-block-content has tabindex="0", so keyboard users can focus it and scroll it. Set tabindex="-1" to remove the tab stop.
  • Floating actions show when focus is inside the block, not only on hover, so keyboard users can reach them.
  • Line numbers are generated content, so they are not read by screen readers.
  • Diff lines carry a + or − marker as well as a tint, so the change does not rely on color.
  • z-code-block-copy-button is labelled "Copy", and a polite live region announces "Copied" after a successful copy.
  • Give a wrap toggle aria-pressed so its state is announced.
  • Give a Show More button aria-expanded and point aria-controls at the id of z-code-block-content.

API Reference

z-code-block, [z-code-block]

The surface that holds the header, the content and the footer.

Prop
[zType]

Visual variant; destructive is for error output

Type
'default' | 'destructive'
Default
'default'
[zSize]

Size; sm has tighter padding and text-xs code, for tool output

Type
'default' | 'sm'
Default
'default'
[class]

Custom CSS classes

Type
ClassValue
Default
''

z-code-block-header, [z-code-block-header]

Row above the content for a title and actions.

Prop
[class]

Custom CSS classes

Type
ClassValue
Default
''

z-code-block-title, [z-code-block-title]

Filename or label, with an optional ng-icon. A long title truncates.

Prop
[class]

Custom CSS classes

Type
ClassValue
Default
''

z-code-block-actions, [z-code-block-actions]

Holds buttons at the end of the header. As a direct child of z-code-block it floats at the top end, hidden until the block is hovered or has focus inside (always visible on touch screens).

Prop
[class]

Custom CSS classes

Type
ClassValue
Default
''

z-code-block-copy-button

Ghost icon button that copies its value to the clipboard and announces "Copied" in a polite live region.

Prop
[zValue]

Text to copy (required)

Type
string
Default
—
[zDisabled]

Disables the button, such as while streamed code is incomplete

Type
boolean
Default
false
[class]

Custom CSS classes for the button

Type
ClassValue
Default
''

z-code-block-content, [z-code-block-content]

The scrollable, keyboard-focusable code area; it is always dir="ltr". Project a string, or z-code-block-line children when lines need a type or highlighted tokens.

Prop
[zWrap]

Wrap long lines instead of scrolling horizontally

Type
boolean
Default
false
[zLineNumbers]

Number each line. A string is split into lines; numbers are not selectable or copied

Type
boolean
Default
false
[zStartLine]

Number of the first line when zLineNumbers is set

Type
number
Default
1
[class]

Custom CSS classes

Type
ClassValue
Default
''

z-code-block-line, [z-code-block-line]

One line of code.

Prop
[zType]

State of the line; added and removed also draw a + or − marker

Type
'default' | 'added' | 'removed' | 'highlighted'
Default
'default'
[zTokens]

One line returned by highlightCode(); the projected text is hidden while it is set

Type
ZardCodeBlockLineTokens
Default
—
[class]

Custom CSS classes

Type
ClassValue
Default
''

z-code-block-footer, [z-code-block-footer]

Row below the content, for example for a Show more button.

Prop
[class]

Custom CSS classes

Type
ClassValue
Default
''

injectHighlightedCode(code, language)

The highlighted lines of code as a signal, for @for + [zTokens] (the counterpart of the shadcn/ui useHighlightedCode hook). Call it in an injection context. It returns plain lines until Shiki has run, highlights again when a signal argument changes, keeps the colors of unchanged lines while code streams, and holds a server render until the lines are ready.

Prop
code

The code, or a function / signal that returns it

Type
string | (() => string)
Default
—
language

A language or alias of code-block.highlight.ts, or ansi; or a function / signal that returns it

Type
string | (() => string)
Default
—
returns

One list of tokens per line

Type
Signal<ZardCodeBlockLineTokens[]>
Default
—

highlightCode(code, language)

Optional syntax highlighting with Shiki (JavaScript regex engine, no WASM). Shiki and each language load on first use, and it runs on the server. Returns tokens, not HTML: render each line with [zTokens].

Prop
code

The code to highlight; one trailing newline is ignored

Type
string
Default
—
language

A language of code-block.highlight.ts, an alias (ts, js, sh, yml...) or ansi for terminal output. Any other value gives plain lines

Type
string
Default
—
returns

One list of tokens per line, with light and dark colors; blank lines are empty lists

Type
Promise<ZardCodeBlockLineTokens[]>
Default
—
github iconwhatsapp icondiscord iconX icon

Made with ❤ in Brazil. Open source and available on GitHub .