← Back to Angular, page 4

angular-0074 · Medium mid

How do you write a custom structural directive, and what do TemplateRef, ViewContainerRef, the context object and the template guard do?

A structural directive receives the template it is attached to as a TemplateRef and decides whether and how often to render it through ViewContainerRef.createEmbeddedView. The asterisk syntax is sugar for an ng-template. A context object provides variables such as let-index, and ngTemplateContextGuard gives those variables correct types.

Full answer

*appRepeat="3" is shorthand. Angular rewrites it to <ng-template [appRepeat]="3">...</ng-template>. A structural directive injects that template and renders it zero or more times.

The pieces:

  • TemplateRef<C> is the template with its context type C.
  • ViewContainerRef is the place where views are inserted. createEmbeddedView(templateRef, context) creates one, and clear() removes all of them.
  • The context is an object. $implicit is the default value for let-item, and other keys are named: let-i="index".
  • input() gives the directive's value (appRepeat). Inside an effect, the directive re-renders when the input changes.
  • static ngTemplateContextGuard is a type guard that tells the compiler the shape of the context, so let-i="index" is typed as a number rather than any. ngTemplateGuard_appRepeat can narrow the input type as ngIf does.

Microsyntax lets users write *appRepeat="3; let i = index". The part after the first ; binds context names. An extra input can be bound with the directive's selector prefix: *appRepeat="3; gap: 10" sets an input named appRepeatGap.

When to write one: a reusable structure that control flow cannot express, such as role-based rendering (*appHasRole="'admin'"), a permissions check, or a template with repeated context. When not: for conditions and loops, @if and @for are faster and typed already, and the old *ngIf and *ngFor are legacy.

Remember to destroy views you create. clear() does it, and the container destroys remaining views when the directive is destroyed.

typescript
import { Component, Directive, TemplateRef, ViewContainerRef, effect, inject, input } from '@angular/core';

interface RepeatContext {
  $implicit: number;
  index: number;
  count: number;
}

@Directive({ selector: '[appRepeat]' })
export class RepeatDirective {
  readonly times = input.required<number>({ alias: 'appRepeat' });

  private readonly template = inject(TemplateRef<RepeatContext>);
  private readonly container = inject(ViewContainerRef);

  constructor() {
    effect(() => {
      const count = Math.max(0, Math.floor(this.times()));
      this.container.clear();
      for (let i = 0; i < count; i++) {
        this.container.createEmbeddedView(this.template, { $implicit: i + 1, index: i, count });
      }
    });
  }

  // Gives the compiler the context type, so let-index is a number.
  static ngTemplateContextGuard(_dir: RepeatDirective, _ctx: unknown): _ctx is RepeatContext {
    return true;
  }
}

@Component({
  selector: 'app-rows',
  imports: [RepeatDirective],
  template: `
    <ul>
      <li *appRepeat="3; let n; let i = index; let total = count">Row {{ n }} (index {{ i }} of {{ total }})</li>
    </ul>
  `,
})
export class RowsComponent {}

Angular 20.3, strict template check passes. A Karma test in headless Chrome renders the repeat three times and checks the text of the last row. Use as `<p *appRepeat="3; let i = index">Row {{ i }}</p>`.

Key points

  • `*dir` is sugar for `<ng-template [dir]>`.
  • `TemplateRef` plus `ViewContainerRef.createEmbeddedView(template, context)` renders the content.
  • `$implicit` and named keys form the context. `ngTemplateContextGuard` types them.
  • Prefer built-in control flow unless you need custom structure.

Common mistakes

  • Forgetting `clear()` before re-rendering, which duplicates content.
  • Leaving the context untyped, so every `let-` variable is `any`.
  • Writing a structural directive for a plain condition that `@if` handles.

Follow-ups

  • How does Angular desugar `*appRepeat="3; let i = index"`?
  • How does `ngIf` narrow the type of its input?
  • How would you add an else template?

Tips

  • Show the desugared form to prove you know what the asterisk does.
  • Mention the type guard. It is the detail that separates a quick answer from a complete one.
  • Say that for conditions you would use `@if`.

Evaluation rubric

  • Understands the template and container model.
  • Uses context and microsyntax correctly.
  • Knows when not to write one.