Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 74 ยท Components in Depth

Attribute and Structural Directives

Build Angular attribute directives with host listeners and inputs, compose them with hostDirectives, and learn how structural directives and ng-template work.

A component is a directive with a template. A directive without a template is something more modest: a piece of behavior you attach to an element that already exists. Highlight a row on hover, trim whitespace in an input, show a tooltip, log a click, hide an element unless the user has a role. Instead of repeating that code in every component, you write it once as a directive and use it as an attribute.

Angular has two kinds of directives you write yourself. Attribute directives change how an element looks or behaves. Structural directives add or remove parts of the page by working with <ng-template>. This lesson builds one of each, explains how the * shorthand really works, and shows how directives combine. Directives build on the ideas in Template Refs, View Queries and Host Bindings, especially the host metadata.

Real Angular vs stand-in. The typescript and html blocks that use @Directive are real Angular and read-only here, because the site cannot run the Angular compiler. The runnable examples are stand-ins written in plain TypeScript and JavaScript that model the idea: a registry that matches selectors to elements, and a tiny view container. They are not Angular's code.

An attribute directive

Here is a directive that highlights an element while the pointer is over it. The selector is written in square brackets, which means "match any element that has this attribute":

TypeScript
import { Directive, computed, input, signal } from '@angular/core';

@Directive({
  selector: '[appHighlight]',
  host: {
    '(mouseenter)': 'active.set(true)',
    '(mouseleave)': 'active.set(false)',
    '[style.backgroundColor]': 'active() ? background() : null',
  },
})
export class HighlightDirective {
  color = input('', { alias: 'appHighlight' });
  protected active = signal(false);
  protected background = computed(() => this.color() || 'gold');
}

You use it by importing it into the component that needs it and then writing the attribute:

TypeScript
@Component({
  selector: 'app-demo',
  imports: [HighlightDirective],
  template: `
    <p appHighlight>Gold by default</p>
    <p appHighlight="lightblue">Light blue on hover</p>
  `,
})
export class DemoComponent {}

Several points to notice:

  • There is no template, so a directive is declared with @Directive, not @Component.
  • alias: 'appHighlight' makes the input share its name with the selector, which gives the "attribute with a value" style. When the attribute is written without a value, the input receives an empty string, so the example falls back to 'gold' with ||.
  • The host object (from the previous lesson) sets listeners and bindings on the element the directive sits on.
  • Directives are standalone by default in current Angular, so they are used through imports, not through modules.
  • Use a custom prefix (app above) for your selectors so they never collide with HTML attributes or other libraries.

You can also reach the element with inject(ElementRef) or modify it through Renderer2, but bindings in host are almost always simpler and work with server-side rendering.

A directive can expose itself to the template with exportAs: 'highlight', so a template can write #h="highlight" and read h.active(), just like #form="ngForm".

Stand-in: how directives find their elements

Angular's compiler matches every selector to every element at build time. The stand-in below does the same at runtime, in plain TypeScript, with small objects instead of DOM nodes. A registry maps selectors to directive classes, instantiates the right ones for each element, and wires up their listeners. One element can get several directives at once.

TypeScript Stand-in: a registry that attaches directives

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.

Notice that the button received two directives, and that the span with appConfirm got none, because button[appConfirm] only matches buttons. Selectors with a tag name narrow where a directive can apply, which is a good way to prevent misuse.

Combining behavior: directive composition

When you need the same behavior on a component or directive every time, don't make users add the attributes themselves. Host directives include other standalone directives on the host automatically:

TypeScript
@Component({
  selector: 'app-product-card',
  hostDirectives: [
    { directive: HighlightDirective, inputs: ['appHighlight: hoverColor'] },
  ],
  template: `<ng-content />`,
})
export class ProductCardComponent {}

The template author now writes <app-product-card hoverColor="honeydew"> and the highlight behavior comes along. Only the inputs and outputs you list are exposed. This is composition instead of inheritance: small directives, each doing one thing, combined where needed.

Structural directives and ng-template

An attribute directive changes an element. A structural directive decides whether an element exists at all, and how many times. Remember from Content Projection that an <ng-template> is a blueprint that does not render by itself. A structural directive receives that blueprint and uses it to create views.

The * you see on legacy built-ins such as *ngIf and *ngFor is shorthand. Angular rewrites it before your directive sees anything:

HTML
<!-- what you write -->
<p *appUnless="loggedIn">Please sign in.</p>

<!-- what Angular compiles it to -->
<ng-template [appUnless]="loggedIn">
  <p>Please sign in.</p>
</ng-template>
flowchart LR
  A["p with *appUnless"] -->|"desugar"| B["ng-template [appUnless]"]
  B --> C["Directive injects<br/>TemplateRef + ViewContainerRef"]
  C -->|"createEmbeddedView()"| D["p appears in the page"]
  C -->|"clear()"| E["p removed"]

The star is only syntax: the directive receives the template and decides when to render it.

A directive that works with the template injects two things. TemplateRef is the blueprint, and ViewContainerRef is the place in the page where views can be created or removed:

TypeScript
import { Directive, Input, TemplateRef, ViewContainerRef, inject } from '@angular/core';

@Directive({ selector: '[appUnless]' })
export class UnlessDirective {
  private templateRef = inject(TemplateRef);
  private viewContainer = inject(ViewContainerRef);
  private hasView = false;

  @Input() set appUnless(condition: boolean) {
    if (!condition && !this.hasView) {
      this.viewContainer.createEmbeddedView(this.templateRef);
      this.hasView = true;
    } else if (condition && this.hasView) {
      this.viewContainer.clear();
      this.hasView = false;
    }
  }
}

The setter runs each time the bound value changes, so the directive creates or clears the view as needed. A setter with @Input is the traditional form; a directive can also read a signal input() inside an effect(), which works but is less common.

createEmbeddedView takes an optional context, the same idea as ngTemplateOutlet. That is how a directive can offer variables to the template:

HTML
<li *appRepeat="3; let i = index">Row {{ i + 1 }}</li>

The part after the semicolon is microsyntax: let i = index binds the template variable i to the index key of the context. Extra keys in the microsyntax bind to further inputs: of: items would set an input named appRepeatOf.

Built-in structural directives (*ngIf, *ngFor, *ngSwitch) still work, but they are legacy. The control-flow blocks @if, @for and @switch replace them, and recent Angular versions have started deprecating them. Writing your own structural directive is rare now, but it remains the right tool for things like permissions (*appHasRole="'admin'") or custom lazy rendering.

Stand-in: a view container

This example models TemplateRef, ViewContainerRef and two structural directives. A "template" is a function that returns a string, and the container keeps the created views, so you can see exactly what the directives do.

TypeScript Stand-in: unless and repeat structural directives

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 hasView flag in UnlessDirective stops it from doing any work when the same value arrives twice, as in the third line of output. RepeatDirective simply clears and rebuilds, which is the simplest correct approach (the real @for does much smarter diffing, covered in Control Flow).

Both kinds on a real page

Finally, a browser stand-in using real DOM nodes. Elements with a data-highlight attribute get hover behavior, and a <template> element plays the role of ng-template for the "unless" behavior. Toggle the checkbox to create or remove the message.

Stand-in: attribute and structural behavior in the DOM

Recursive templates and components

Some data is a tree of unknown depth: folders inside folders, nested comments, a category menu. A template for it has to render itself. Angular offers two ways.

The first is a component that uses its own selector. A standalone component may appear in its own template, so a tree node can render its children as more tree nodes:

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

export interface Folder {
  name: string;
  children?: Folder[];
}

@Component({
  selector: 'app-folder',
  template: `
    <li>
      {{ node().name }}
      @if (node().children?.length) {
        <ul>
          @for (child of node().children; track child.name) {
            <app-folder [node]="child" />
          }
        </ul>
      }
    </li>
  `,
})
export class FolderComponent {
  node = input.required<Folder>();
}

The second is an <ng-template> that renders itself through ngTemplateOutlet. It keeps everything in one component and passes the data in through the context:

HTML
<ng-template #level let-nodes>
  <ul>
    @for (node of nodes; track node.name) {
      <li>
        {{ node.name }}
        @if (node.children) {
          <ng-container *ngTemplateOutlet="level; context: { $implicit: node.children }" />
        }
      </li>
    }
  </ul>
</ng-template>

<ng-container *ngTemplateOutlet="level; context: { $implicit: roots() }" />

In both versions, recursion needs an end condition: a node with no children renders nothing more. Data with a cycle (a node that contains itself) would recurse forever, so guard against it when the tree comes from outside. The same idea applies to a recursive structural directive, one whose template includes elements that use the directive again. Remember that the directive's own host element is only the starting point; the recursion lives in the template it creates.

TypeScript Stand-in: a template that renders itself

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.

Choosing between a directive, a component and a pipe

  • Use a component when you need your own template.
  • Use an attribute directive to add behavior or styling to existing elements, especially when it should apply to many kinds of elements.
  • Use a structural directive only when you must control whether markup exists, based on custom logic. For ordinary conditions and lists, use @if and @for.
  • Use a pipe for transforming a value shown in the template; pipes are covered in their own lesson.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the selector [appHighlight] match?

    Square brackets mean an attribute selector. To restrict by tag, write something like button[appConfirm].
  2. 2. What is *appUnless="cond" shorthand for?

    The star wraps the element in an ng-template and binds the value to the directive's input. The directive then decides whether to create the view.
  3. 3. Which two things does a structural directive typically inject to render its content?

    TemplateRef is the blueprint; ViewContainerRef is where views are created (createEmbeddedView) or removed (clear).
  4. 4. What does hostDirectives let a component do?

    It is composition: the directive's behavior is applied to the component's host, and only the inputs and outputs you list are public.
  5. 5. Why does <p appHighlight> pass an empty string to an input aliased appHighlight?

    A static attribute with no value is an empty string, so code such as this.color() || 'gold' supplies the default.

Summary

  • A directive is behavior without a template. Attribute directives use a selector such as [appHighlight] and are imported into the components that use them.
  • Use host bindings and listeners to affect the element the directive sits on, and an aliased input to pass a value through the same attribute.
  • hostDirectives composes standalone directives onto a component or directive, exposing only the inputs and outputs you list.
  • * is syntax for an <ng-template>; a structural directive injects TemplateRef and ViewContainerRef and calls createEmbeddedView and clear.
  • @if, @for and @switch replace the built-in structural directives; write your own only when the control-flow blocks cannot express the behavior.

Next: Signals: signal, computed and effect