Blog

Part 11 · Directives in Angular: Attribute Directives, host and hostDirectives

A directive adds behaviour to an element you already have, without a template of its own. This part covers attribute directives, host bindings and listeners, directive inputs, exportAs and hostDirectives.

Some behaviour doesn’t belong to one component. Highlight a row when the mouse is over it. Put the cursor in a field when the page opens. Close a menu on a click somewhere else. You want to add these to elements you already have, without wrapping each in a new component. That’s what a directive does.

This part covers attribute directives: the @Directive decorator, the host setting for bindings and listeners, directive inputs and outputs, exportAs, and hostDirectives, which builds a directive into a component. In Part 7 we used host to put classes on a component’s own tag, and in Part 10 we reached into the DOM with viewChild and afterNextRender. Here we use both from the outside. Every example here is a whole file you can paste into your practice project from Part 1. Each one was built with Angular 22.3 and run in a browser before this was published.

Try this first

This example has two files. The first is a directive. Save it as src/app/highlight.ts:

// src/app/highlight.ts
import { Directive, signal } from '@angular/core';

@Directive({
  selector: '[appHighlight]',
  host: { '(click)': 'toggle()', '[class.on]': 'on()' },
})
export class Highlight {
  protected readonly on = signal(false);

  protected toggle() {
    this.on.update((value) => !value);
  }
}

The second puts it on three buttons:

// src/app/app.ts
import { Component } from '@angular/core';
import { Highlight } from './highlight';

@Component({
  selector: 'app-root',
  imports: [Highlight],
  template: `
    <button appHighlight>Tea</button>
    <button appHighlight>Coffee</button>
    <button appHighlight>Juice</button>
  `,
  styles: `
    .on {
      background: gold;
    }
  `,
})
export class App {}

Before you read on, guess. Click Tea, then Juice, then Tea again. Which buttons are gold? There’s one on signal in the class. Do the three buttons share it?

Only Juice is gold. In the browser’s developer tools (F12, the Elements tab), the buttons look like this:

<button apphighlight="" class="">Tea</button>
<button apphighlight="">Coffee</button>
<button apphighlight="" class="on">Juice</button>

Angular made three Highlight objects, one for each button. Each has its own on signal. Tea went on and off again, which leaves an empty class behind. Juice went on once. (The browser writes attribute names in lower case, so appHighlight shows as apphighlight.)

What a directive is

A directive is a class that Angular attaches to an element in a template. It can set the element’s properties, attributes and classes, and listen to its events. It has no template of its own. It works on the element it’s attached to, which Angular calls its host element.

You’ve used components since Part 1. A component is a directive that also has a template. @Component takes everything @Directive takes, plus template, styles and the like. That’s why the host setting from Part 7 works the same way here.

A directive that changes the element it sits on, without adding or removing elements, is called an attribute directive. You use it like an attribute. There’s also a kind called a structural directive; we’ll meet it near the end.

Writing one: the selector, the name, the import

Three things in the Try-this-first code make it work.

The selector. selector: '[appHighlight]' is a CSS selector. The square brackets mean “any element that has the attribute appHighlight“. Angular checks every element in a template against the selectors of the directives that template can use. Each match gets its own instance.

The names. The Angular style guide says an attribute selector should be in camelCase and use the same prefix as your components. New projects use app, so components are app-user-card and directives are appHighlight. The prefix keeps your names from clashing with real HTML attributes and with libraries. The file is highlight.ts and the class is Highlight, with no .directive suffix. ng generate directive highlight makes exactly that file, class and selector.

The import. A template can use a directive only if its component lists it in imports, the same as a child component in Part 5. Forget it, and something odd happens. We’ll see it in a worked example below.

host: bindings and listeners

A directive can’t write [class.on]="..." in a template, because it doesn’t have one. The host setting is how it binds to its host element instead. Each key is written the way you’d write it on the element, and each value is an expression, in quotes, that runs against the directive class:

  • '[class.on]': 'on()' binds the class on to the signal. You can also bind [style.x], [attr.x] and DOM properties. (Exercise 2 shows a catch with properties.)
  • '(click)': 'toggle()' listens to the host’s click event and calls toggle().
  • A key with no brackets, like role: 'button', sets a plain attribute.

Here’s a highlight that follows the mouse. It listens to two events and keeps its state in a signal:

// src/app/highlight.ts
import { Directive, signal } from '@angular/core';

@Directive({
  selector: '[appHighlight]',
  host: {
    '(mouseenter)': 'hovered.set(true)',
    '(mouseleave)': 'hovered.set(false)',
    '[style.background-color]': "hovered() ? 'yellow' : null",
  },
})
export class Highlight {
  protected readonly hovered = signal(false);
}
// src/app/app.ts
import { Component } from '@angular/core';
import { Highlight } from './highlight';

@Component({
  selector: 'app-root',
  imports: [Highlight],
  template: `
    <p appHighlight>Point at me.</p>
    <p appHighlight>Then at me.</p>
  `,
})
export class App {}

Move the mouse over the first paragraph. It turns yellow, and its HTML is:

<p apphighlight="" style="background-color: yellow;">Point at me.</p>
<p apphighlight="">Then at me.</p>

Move the mouse off the paragraphs, and the colour goes:

<p apphighlight="" style="">Point at me.</p>
<p apphighlight="">Then at me.</p>

Binding a style to null removes it, so the paragraph goes back to how it was. (An empty style attribute is left behind; it does nothing.)

An event calls set on a signal, the host binding reads it, and Angular updates the element. Nothing touches the DOM by hand.

A few more things host listeners can do:

  • Pass the event. '(keydown)': 'onKey($event)' hands the event object to a method, as $event did in Part 2.
  • Filter keys. '(keydown.enter)': 'toggle()' runs only for the Enter key.
  • Listen outside the host. '(document:click)': '...' listens on the whole document, and window: and body: work the same way. Angular removes the listener when the directive is destroyed. We’ll use this for a menu below.

As in Part 7, these expressions are type-checked: a misspelt 'hoverd.set(true)' fails with TS2551. Members only the host uses can be protected, like hovered.

Directive inputs

A directive takes inputs like a component. A common pattern is to give one input the same name as the selector:

// src/app/highlight.ts
import { Directive, input } from '@angular/core';

@Directive({
  selector: '[appHighlight]',
  host: { '[style.background-color]': 'appHighlight()' },
})
export class Highlight {
  readonly appHighlight = input('yellow');
}

Now one attribute does two jobs. It attaches the directive, and it passes a value:

// src/app/app.ts
import { Component, signal } from '@angular/core';
import { Highlight } from './highlight';

@Component({
  selector: 'app-root',
  imports: [Highlight],
  template: `
    <p appHighlight>One</p>
    <p appHighlight="pink">Two</p>
    <p [appHighlight]="color()">Three</p>
  `,
})
export class App {
  protected readonly color = signal('lightblue');
}

No alias is needed: the class field is called appHighlight, so the input is too. appHighlight="pink" passes the text pink, and [appHighlight]="color()" passes an expression, as in Part 5. The bracketed form still matches the selector [appHighlight]. Angular looks at binding names when it matches selectors, not only at plain attributes.

Now guess: which paragraphs get a colour? The rendered HTML is:

<p apphighlight="">One</p>
<p apphighlight="pink" style="background-color: pink;">Two</p>
<p style="background-color: lightblue;">Three</p>

One has no colour, even though the input’s default is 'yellow'. A bare attribute is an attribute with an empty value: appHighlight means appHighlight="". Angular passes that empty string to the input, and it replaces the default. background-color: '' isn’t a colour, so nothing is set.

The fix is to treat an empty value as “use the default”. A computed does that:

// src/app/highlight.ts
import { Directive, computed, input } from '@angular/core';

@Directive({
  selector: '[appHighlight]',
  host: { '[style.background-color]': 'color()' },
})
export class Highlight {
  readonly appHighlight = input('');
  protected readonly color = computed(() => this.appHighlight() || 'yellow');
}

With the same app.ts, One is now yellow. || means “if the left side is empty, use the right side”. The input’s default is '' now, because it no longer matters.

If you’d rather call the field something else inside the class, use alias from Part 5: readonly color = input('', { alias: 'appHighlight' }). A directive can have more inputs too. They’re just more attributes on the same element: <p appHighlight="pink" [hoverOnly]="true">.

A directive can also have outputs, made with output() as in Part 6. The parent listens with (name)="..." on the host element. We’ll write one in the first worked example.

A directive attached to its host

Here’s everything a directive does, in one picture:

App's template <p [appHighlight]="color()">Hi</p> creates the element input: appHighlight host element <p>Hi</p> directive Highlight hovered [class.on] [style.background-color] (mouseenter) (mouseleave) Solid: the directive sets things on the element. Dashed red: the element's events call the directive.

A directive has no template. It reads inputs from the template that uses it, sets bindings on its host element, and listens to the host’s events.

The element belongs to App’s template. The directive only adds to it: a class, a style, a listener. Two directives can sit on the same element, each adding its own part.

ElementRef: when you really need the element

You can also ask Angular for the host element itself, with inject(ElementRef). Its nativeElement is the real DOM element. Angular’s own guide shows the highlight written that way:

private readonly el = inject(ElementRef);
// ...
this.el.nativeElement.style.backgroundColor = 'yellow';

It works, but prefer host bindings when a binding can do the job:

  • A host binding is checked at build time. nativeElement is typed any unless you say otherwise, so a typo in style.backgroundColr builds fine and does nothing.
  • Angular owns the element. A binding goes through Angular, which knows what it set and can change it back. A direct write is invisible to it.
  • Code that pokes the DOM may not work during server rendering (Part 29), where there’s no real browser, and can confuse hydration.

Some jobs need the element, though. Calling a DOM method like focus() or contains(), or measuring a size, can’t be written as a binding. Here’s a directive that puts the cursor in its field when the page opens:

// src/app/autofocus.ts
import { Directive, ElementRef, afterNextRender, inject } from '@angular/core';

@Directive({ selector: '[appAutofocus]' })
export class Autofocus {
  private readonly host = inject(ElementRef<HTMLElement>);

  constructor() {
    afterNextRender(() => this.host.nativeElement.focus());
  }
}
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { Autofocus } from './autofocus';

@Component({
  selector: 'app-root',
  imports: [Autofocus],
  template: `
    <label>Name <input appAutofocus #name (input)="typed.set(name.value)" /></label>
    <p>You typed: {{ typed() }}</p>
  `,
})
export class App {
  protected readonly typed = signal('');
}

ElementRef<HTMLElement> says what kind of element to expect, so nativeElement has a real type and focus() is checked. afterNextRender, from Part 10, waits until the element is on the page. In the constructor the element may not be on the page yet: inside @if or @for it isn’t, and focus() does nothing. #name is a template reference variable from Part 2.

Load the page and type Hi without clicking anything. The page shows:

Name
You typed: Hi

The keys went into the field, because the directive had already focused it.

exportAs: using the directive from the template

Sometimes the template around a directive wants to read its state. exportAs gives the directive a name that a template reference variable can point at:

// src/app/tooltip.ts
import { Directive, input, signal } from '@angular/core';

@Directive({
  selector: '[appTooltip]',
  exportAs: 'appTooltip',
  host: {
    '(focusin)': 'visible.set(true)',
    '(focusout)': 'visible.set(false)',
    '(mouseenter)': 'visible.set(true)',
    '(mouseleave)': 'visible.set(false)',
  },
})
export class Tooltip {
  readonly appTooltip = input.required<string>();
  private readonly visible = signal(false);
  readonly shown = this.visible.asReadonly();
}
// src/app/app.ts
import { Component } from '@angular/core';
import { Tooltip } from './tooltip';

@Component({
  selector: 'app-root',
  imports: [Tooltip],
  template: `
    <label>Email <input appTooltip="We never share it." #tip="appTooltip" /></label>
    @if (tip.shown()) {
      <p>{{ tip.appTooltip() }}</p>
    }
  `,
})
export class App {}

#tip="appTooltip" means “call the Tooltip directive on this element tip“. Without the ="appTooltip" part, #tip would be the <input> element, as in Part 2. Now the template can read the directive’s public members: tip.shown() and tip.appTooltip().

shown is the read-only view of a private signal, from Part 3. The template can read it but can’t set it. Only the directive’s own listeners change it. focusin and focusout are like focus and blur, but they also fire when something inside the host gains or loses focus. That will matter in a worked example.

Click into the field (or press Tab until you get there). The page shows:

Email
We never share it.

Press Tab to leave it, and the hint goes:

Email

The directive knows when to show the hint. The template decides how it looks.

hostDirectives: a directive built into a component

Say you have a Selectable directive. It makes any element toggle a selected state on click or Enter, marks it with a class and aria-pressed for screen readers, and makes it reachable with Tab. Now you write a Chip component, and every chip should be selectable. You could ask every parent to write <app-chip appSelectable>. Someone will forget.

hostDirectives builds the directive into the component instead. Every <app-chip> gets one, and parents don’t have to know:

// src/app/selectable.ts
import { Directive, model } from '@angular/core';

@Directive({
  host: {
    role: 'button',
    tabindex: '0',
    '[attr.aria-pressed]': 'selected()',
    '[class.selected]': 'selected()',
    '(click)': 'toggle()',
    '(keydown.enter)': 'toggle()',
  },
})
export class Selectable {
  readonly selected = model(false);

  toggle() {
    this.selected.update((value) => !value);
  }
}
// src/app/chip.ts
import { Component, inject, input } from '@angular/core';
import { Selectable } from './selectable';

@Component({
  selector: 'app-chip',
  hostDirectives: [{ directive: Selectable, inputs: ['selected'], outputs: ['selectedChange'] }],
  template: `{{ selectable.selected() ? '✓ ' : '' }}{{ label() }}`,
  styles: `
    :host {
      border: 1px solid gray;
      padding: 2px 8px;
    }
    :host(.selected) {
      background: lightgreen;
    }
  `,
})
export class Chip {
  readonly label = input.required<string>();
  protected readonly selectable = inject(Selectable);
}
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { Chip } from './chip';

@Component({
  selector: 'app-root',
  imports: [Chip],
  template: `
    <app-chip label="Tea" [(selected)]="tea" />
    <app-chip label="Coffee" />
    <p>Tea: {{ tea() }}</p>
  `,
})
export class App {
  protected readonly tea = signal(true);
}

Several new things:

  • Selectable has no selector. A directive used only through hostDirectives doesn’t need one; Angular ignores the selector there anyway.
  • hostDirectives lists directives that Angular attaches to the component’s host element, <app-chip>, whenever the component is used. App imports only Chip.
  • By default, the directive’s inputs and outputs aren’t part of the component’s public API. inputs: ['selected'] and outputs: ['selectedChange'] pass them through, so a parent can bind them on <app-chip>. Because selected is a model(), passing both through gives two-way binding with [(selected)], as in Part 6.
  • The component can inject its host directive and read its state. Chip shows a tick when selectable.selected() is true.
  • role: 'button' makes a screen reader announce the chip as a button, and tabindex: '0' puts it in the Tab order.

Click Coffee, then Tea. The page shows:

Tea✓ Coffee
Tea: false

The two chips sit on one line, so the page text runs them together: Tea and ✓ Coffee. Tea started selected, because App’s tea signal is true, and the click turned it off. App’s signal followed it. Coffee has no binding, so its directive keeps its own state.

You can rename what you pass through, with a colon: inputs: ['selected: on'] lets a parent write [on]. One limit: hostDirectives is fixed when the component is compiled. You can’t add or remove one at run time.

Structural directives, briefly

There’s a second kind of directive. A structural directive decides whether, or how many times, a piece of template is drawn. Before Angular 17, that’s how *ngIf and *ngFor worked. They still exist in Angular 22, but they’ve been deprecated since Angular 20. The * is shorthand: <p *ngIf="ok"> wraps the <p> in an <ng-template> from Part 9, and the directive decides when to create it. You can still write your own, with inject(TemplateRef) and inject(ViewContainerRef). You’ll rarely need to. @if, @for and @switch from Part 4 cover what most structural directives did, and they’re built into the template language, with nothing to import.

Worked example: closing a menu on a click outside

A menu should close when you click anywhere else on the page. The menu itself can’t see those clicks. They happen on other elements. So we listen on the whole document and ask: was this click inside my host?

// src/app/click-outside.ts
import { Directive, ElementRef, inject, output } from '@angular/core';

@Directive({
  selector: '[appClickOutside]',
  host: { '(document:click)': 'onDocumentClick($event)' },
})
export class ClickOutside {
  readonly appClickOutside = output<void>();
  private readonly host = inject(ElementRef<HTMLElement>);

  protected onDocumentClick(event: MouseEvent) {
    if (!this.host.nativeElement.contains(event.target as Node)) {
      this.appClickOutside.emit();
    }
  }
}
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { ClickOutside } from './click-outside';

@Component({
  selector: 'app-root',
  imports: [ClickOutside],
  template: `
    <div (appClickOutside)="open.set(false)">
      <button (click)="open.set(!open())">Menu</button>
      @if (open()) {
        <button>Rename</button>
        <button>Delete</button>
      }
    </div>
    <button>Elsewhere</button>
    <p>Menu is {{ open() ? 'open' : 'closed' }}</p>
  `,
})
export class App {
  protected readonly open = signal(false);
}

How it fits together:

  • '(document:click)' hears every click on the page. Each ClickOutside gets its own listener, and Angular removes it when the directive is destroyed.
  • contains() is a DOM method: it says whether one element is inside another (or is the same one). That’s why this directive needs ElementRef. No binding can ask that question.
  • event.target is typed EventTarget | null, and contains() wants a Node. as Node tells TypeScript “trust me, it’s a node”. A click always has an element as its target, so that’s safe here.
  • The output has the same name as the selector, so (appClickOutside)="..." both attaches the directive and listens to it. output<void>() sends an event with no value.

Click Menu, then Rename. The page shows:

MenuRenameDelete
Elsewhere
Menu is open

The click on Rename was inside the <div>, so the menu stayed open. Now click Elsewhere:

Menu
Elsewhere
Menu is closed

What about the Menu button? Its click is inside the host too, so the directive stays quiet and only the button’s own (click) runs. If the directive sat on a <div> that holds only the menu items and not the Menu button, a click on Menu would count as outside: the menu would open and close in the same click.

Worked example: an icon button that brings its own tooltip

An icon button shows only a symbol, so it needs a label for screen readers and a tooltip for everyone else. Our Tooltip directive from the exportAs section already knows when to show. With hostDirectives, an IconButton component can use it, and draw the tooltip itself:

// src/app/tooltip.ts
import { Directive, input, signal } from '@angular/core';

@Directive({
  selector: '[appTooltip]',
  exportAs: 'appTooltip',
  host: {
    '(focusin)': 'visible.set(true)',
    '(focusout)': 'visible.set(false)',
    '(mouseenter)': 'visible.set(true)',
    '(mouseleave)': 'visible.set(false)',
  },
})
export class Tooltip {
  readonly appTooltip = input.required<string>();
  private readonly visible = signal(false);
  readonly shown = this.visible.asReadonly();
}
// src/app/icon-button.ts
import { Component, inject, input } from '@angular/core';
import { Tooltip } from './tooltip';

@Component({
  selector: 'app-icon-button',
  hostDirectives: [{ directive: Tooltip, inputs: ['appTooltip: tip'] }],
  template: `
    <button [attr.aria-label]="tooltip.appTooltip()">{{ icon() }}</button>
    @if (tooltip.shown()) {
      <span role="tooltip">{{ tooltip.appTooltip() }}</span>
    }
  `,
})
export class IconButton {
  readonly icon = input.required<string>();
  protected readonly tooltip = inject(Tooltip);
}
// src/app/app.ts
import { Component } from '@angular/core';
import { IconButton } from './icon-button';

@Component({
  selector: 'app-root',
  imports: [IconButton],
  template: `
    <app-icon-button icon="✎" tip="Edit" />
    <app-icon-button icon="✕" tip="Delete" />
  `,
})
export class App {}

Notice:

  • inputs: ['appTooltip: tip'] passes the directive’s input through under a shorter name. Parents write tip="Delete"; inside, it’s still appTooltip.
  • The tooltip directive sits on <app-icon-button>, but focus goes to the <button> inside it. focus and blur don’t bubble up to parent elements, so a (focus) listener on the host would never fire. focusin and focusout do bubble. That’s why we chose them.
  • The same text is the button’s aria-label, so a screen reader says “Delete, button” while sighted users see the tooltip.

Load the page and press Tab twice, to reach the second button. The page shows:

✎✕Delete

The tooltip Delete appears after the second icon. (The buttons and the tooltip sit on one line.) Press Tab again, and it goes:

✎✕

The mouse works too. Point at the first icon, and its tooltip shows:

✎Edit✕

Move the mouse away, and it goes again:

✎✕

A parent can still use exportAs on a host directive: <app-icon-button tip="Delete" #t="appTooltip" /> gives it the same Tooltip instance.

Worked example: a directive that does nothing

A teammate adds the highlight from the inputs section to a new page. They write the directive’s file, use it, and forget one line:

// src/app/highlight.ts
import { Directive, computed, input } from '@angular/core';

@Directive({
  selector: '[appHighlight]',
  host: { '[style.background-color]': 'color()' },
})
export class Highlight {
  readonly appHighlight = input('');
  protected readonly color = computed(() => this.appHighlight() || 'yellow');
}
// src/app/app.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `<p appHighlight="pink">Important</p>`,
})
export class App {}

It builds with no error and no warning. The page shows:

Important

and the paragraph isn’t pink. The HTML is:

<p apphighlight="pink">Important</p>

The attribute is there, but there’s no style. Without imports: [Highlight], Angular doesn’t know the directive exists, so appHighlight="pink" is just an HTML attribute the browser doesn’t understand. Browsers accept any attribute, and Angular doesn’t check plain attributes, so the build has nothing to complain about.

Now they try the bound form, still without the import:

// src/app/app.ts
import { Component, signal } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `<p [appHighlight]="color()">Important</p>`,
})
export class App {
  protected readonly color = signal('pink');
}
✘ [ERROR] NG8002: Can't bind to 'appHighlight' since it isn't a known property of 'p'. Find more at https://next.angular.dev/errors/NG8002 [plugin angular-compiler]

This time the build fails. [appHighlight] is a property binding, and Angular checks property bindings. No directive on this <p> has an appHighlight input, and <p> elements have no appHighlight property, so there’s nothing to bind to. NG8002 is the same error Part 2 showed for a misspelt property. When the name is a directive’s input, it almost always means a missing import.

The fix for both is one line in App:

// src/app/app.ts
import { Component, signal } from '@angular/core';
import { Highlight } from './highlight';

@Component({
  selector: 'app-root',
  imports: [Highlight],
  template: `<p [appHighlight]="color()">Important</p>`,
})
export class App {
  protected readonly color = signal('pink');
}

Now the paragraph is pink, and its HTML is <p style="background-color: pink;">Important</p>.

The static form fails silently; the bound form fails loudly. When a directive seems to do nothing, check imports first. A related slip is a typo in exportAs. #h="appHighlite" fails with NG8003: No directive found with exportAs 'appHighlite', and the same error appears if the directive has no exportAs at all or isn’t imported.

In older code

Older directives put host bindings on class members with decorators: @HostBinding('class.on') on = false; and @HostListener('mouseenter') onEnter() {...}. Angular’s guide says to prefer the host setting, and keeps the decorators for backwards compatibility. Before Angular 19, a directive that wasn’t part of an NgModule had to say standalone: true. Now standalone is the default, and older code that uses NgModules marks its directives standalone: false and lists them in a module’s declarations instead of a component’s imports. You’ll also see @Input(), @Output() and constructor(private el: ElementRef) instead of input(), output() and inject().

Best practices

  • Use host bindings and listeners, not ElementRef, when a binding can do the job. They’re type-checked, and Angular stays in charge of the element. They replace nativeElement.style.x = ... and @HostBinding / @HostListener.
  • Inject ElementRef<HTMLElement> only for DOM methods and measurements, like focus(), contains() or a size. Give it the element type, so nativeElement is checked. Wrap DOM work that needs the page drawn in afterNextRender.
  • Name an input or output after the selector when it’s the main one. [appHighlight]="color" and (appClickOutside)="close()" attach and use the directive in one attribute. It replaces writing appHighlight [color]="color".
  • Use hostDirectives when every use of a component needs the behaviour. The component can’t be used without it, and the directive stays reusable on its own. It replaces copying the same host listeners into several components.
  • Keep a directive’s state in signals, and expose it read-only. shown = visible.asReadonly() lets templates read it through exportAs without changing it.

Tips and traps

  • Forgetting imports. With a static attribute, the directive silently does nothing. With a binding, the build fails with NG8002, Can't bind to 'appHighlight' since it isn't a known property of 'p'. Add the directive to the component’s imports.
  • A bare attribute wipes the default. <p appHighlight> sets an input named appHighlight to '', not to its default. Fall back in a computed: this.appHighlight() || 'yellow'.
  • (focus) on a host that isn’t focusable. It never fires when something inside gets focus, because focus doesn’t bubble. Listen to (focusin) and (focusout).
  • A click-outside directive on the wrong element. If the toggle button isn’t inside the host, its click counts as outside, and the menu closes as soon as it opens. Put the directive on the element that holds both.
  • #tip="appTooltip" fails with NG8003. The name doesn’t match the directive’s exportAs, the directive has no exportAs, or it isn’t imported. Check all three.
  • Can't bind to 'disabled' since it isn't a known property of 'ng-directive'. A host property binding on a directive whose selector is only an attribute. Angular can’t tell what element the host is. Narrow the selector, as in button[appBusy].
  • Expecting a host directive’s inputs on the component. By default they aren’t public. <app-chip [selected]="x"> fails with NG8002 until the component lists inputs: ['selected'].

A directive adds behaviour to an element it doesn’t own: it reads inputs, sets host bindings, listens to host events, and leaves the drawing to the template.

Exercises

Exercise 1. Without running it, guess: you click Menu A, then Menu B. What does the page say? It uses ClickOutside from the first worked example.

// src/app/click-outside.ts
import { Directive, ElementRef, inject, output } from '@angular/core';

@Directive({
  selector: '[appClickOutside]',
  host: { '(document:click)': 'onDocumentClick($event)' },
})
export class ClickOutside {
  readonly appClickOutside = output<void>();
  private readonly host = inject(ElementRef<HTMLElement>);

  protected onDocumentClick(event: MouseEvent) {
    if (!this.host.nativeElement.contains(event.target as Node)) {
      this.appClickOutside.emit();
    }
  }
}
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { ClickOutside } from './click-outside';

@Component({
  selector: 'app-root',
  imports: [ClickOutside],
  template: `
    <div (appClickOutside)="a.set(false)">
      <button (click)="a.set(true)">Menu A</button>
    </div>
    <div (appClickOutside)="b.set(false)">
      <button (click)="b.set(true)">Menu B</button>
    </div>
    <p>A: {{ a() ? 'open' : 'closed' }}, B: {{ b() ? 'open' : 'closed' }}</p>
  `,
})
export class App {
  protected readonly a = signal(false);
  protected readonly b = signal(false);
}

Exercise 2. Write a directive [appBusy] for buttons, in src/app/busy.ts. It has one boolean input named appBusy that defaults to false. While it’s true, the button is disabled and has the attribute aria-busy="true". In App, put it on a Save button whose click sets a saving signal to true, and back to false 100 milliseconds later. Hint: bind [disabled] and [attr.aria-busy] in host. Binding an attribute to null removes it. If the build complains about disabled, read the message closely: what kind of element does Angular think the host is?

Exercise 3. Change Chip from the hostDirectives section so that parents write [(on)]="tea" instead of [(selected)]="tea". Don’t change Selectable. Hint: a two-way binding [(on)] needs an input on and an output onChange.

Answers

1. A is closed and B is open. Each ClickOutside has its own document listener. The click on Menu B is inside B’s <div>, so B opens. It’s outside A’s <div>, so A’s directive emits and A closes. Here’s the run:

Menu A
Menu B
A: closed, B: open

(The buttons are on separate lines because each is inside its own <div>.)

2. With selector: '[appBusy]', the build fails with NG8002: Can't bind to 'disabled' since it isn't a known property of 'ng-directive'. Host bindings are type-checked, and a bare attribute selector could match any element, so Angular can’t tell whether the host has a disabled property. button[appBusy] means “a <button> with the attribute appBusy“. Now the host is a button, and [disabled] is checked against it. [attr.aria-busy] gets 'true' or null, so the attribute is there only while busy:

// src/app/busy.ts
import { Directive, input } from '@angular/core';

@Directive({
  selector: 'button[appBusy]',
  host: {
    '[disabled]': 'appBusy()',
    '[attr.aria-busy]': "appBusy() ? 'true' : null",
  },
})
export class Busy {
  readonly appBusy = input(false);
}
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { Busy } from './busy';

@Component({
  selector: 'app-root',
  imports: [Busy],
  template: `<button [appBusy]="saving()" (click)="save()">Save</button>`,
})
export class App {
  protected readonly saving = signal(false);

  protected save() {
    this.saving.set(true);
    setTimeout(() => this.saving.set(false), 100);
  }
}

A bare <button appBusy> would fail with TS2322, Type 'string' is not assignable to type 'boolean', for the reason we saw with appHighlight. Add transform: booleanAttribute from Part 5 if you want that form. Click Save. Straight after the click, the button’s HTML is:

<button disabled="" aria-busy="true">Save</button>

A moment later it’s back to <button>Save</button>:

3. Rename both with a colon in hostDirectives:

// src/app/selectable.ts
import { Directive, model } from '@angular/core';

@Directive({
  host: {
    role: 'button',
    tabindex: '0',
    '[attr.aria-pressed]': 'selected()',
    '[class.selected]': 'selected()',
    '(click)': 'toggle()',
    '(keydown.enter)': 'toggle()',
  },
})
export class Selectable {
  readonly selected = model(false);

  toggle() {
    this.selected.update((value) => !value);
  }
}
// src/app/chip.ts
import { Component, inject, input } from '@angular/core';
import { Selectable } from './selectable';

@Component({
  selector: 'app-chip',
  hostDirectives: [
    { directive: Selectable, inputs: ['selected: on'], outputs: ['selectedChange: onChange'] },
  ],
  template: `{{ selectable.selected() ? '✓ ' : '' }}{{ label() }}`,
})
export class Chip {
  readonly label = input.required<string>();
  protected readonly selectable = inject(Selectable);
}
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { Chip } from './chip';

@Component({
  selector: 'app-root',
  imports: [Chip],
  template: `
    <app-chip label="Tea" [(on)]="tea" />
    <p>Tea: {{ tea() }}</p>
  `,
})
export class App {
  protected readonly tea = signal(false);
}

Click Tea. The page shows:

✓ Tea
Tea: true

What’s next

Directives add behaviour to elements. In Part 12, we’ll look at pipes, which change how a value is shown in a template, like a date or a price, and see when a computed does the job better.

How useful was this post?

Click on a heart to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.