TExcelTAD
Home › Angular › Custom Directives

Custom Directives

When you find yourself adding the same behaviour to many elements — highlighting on hover, auto-focusing an input, showing a tooltip, tracking clicks — wrap it in your own attribute directive. A directive has no template; it attaches to an existing element through its selector.

A first directive

Generate one with ng generate directive highlight. The selector is an attribute in square brackets, so the directive activates on any element that has a appHighlight attribute:

angular · try it yourself
import { Component, Directive, ElementRef, inject } from '@angular/core';

@Directive({
  selector: '[appHighlight]',
})
export class Highlight {
  private el = inject<ElementRef<HTMLElement>>(ElementRef);

  constructor() {
    this.el.nativeElement.style.backgroundColor = '#fff3a8';
  }
}

@Component({
  selector: 'app-root',
  imports: [Highlight],
  template: `
    <p appHighlight>Directives add behaviour to existing elements.</p>
    <p>This paragraph is not highlighted.</p>
  `,
})
export class App {}

inject(ElementRef) gives the directive the element it sits on. Touching nativeElement directly works, but there is a cleaner way.

Host bindings and listeners

The host property of @Directive binds to the host element's properties, classes, styles and events — declaratively, with the same syntax as templates:

angular · try it yourself
import { Component, Directive, input, signal } from '@angular/core';

@Directive({
  selector: '[appHoverHighlight]',
  host: {
    '[style.backgroundColor]': 'active() ? color() : null',
    '[style.transition]': '"background 0.2s"',
    '(mouseenter)': 'active.set(true)',
    '(mouseleave)': 'active.set(false)',
  },
})
export class HoverHighlight {
  color = input('#ffe3e8', { alias: 'appHoverHighlight' });
  protected active = signal(false);
}

@Component({
  selector: 'app-root',
  imports: [HoverHighlight],
  template: `
    <li appHoverHighlight>Default pink</li>
    <li appHoverHighlight="#d7f5e1">Custom green (hovered)</li>
  `,
})
export class App {}

Things to notice:

  • input(..., { alias: 'appHoverHighlight' }) lets the attribute itself carry the value: appHoverHighlight="#d7f5e1". An empty attribute gives the default.
  • The host bindings read signals, so the style updates automatically.
  • Older code uses @HostBinding and @HostListener decorators instead of host — they do the same job.

Directive logic is plain TypeScript

A directive's behaviour is a small state machine: events come in, state changes, a style comes out. You can model and test that without any DOM:

ts · try it yourself
class HoverState {
  private active = false;

  constructor(private color: string) {}

  enter(): void { this.active = true; }
  leave(): void { this.active = false; }

  background(): string | null {
    return this.active ? this.color : null;
  }
}

const h = new HoverState('#d7f5e1');
const log: (string | null)[] = [h.background()];
h.enter();
log.push(h.background());
h.leave();
log.push(h.background());
console.log(log);
[ null, '#d7f5e1', null ]

A practical directive: auto-focus

Some behaviour must wait until the element is in the page. afterNextRender runs a callback once, after Angular has rendered:

angular · try it yourself
import { Component, Directive, ElementRef, afterNextRender, inject } from '@angular/core';

@Directive({ selector: 'input[appAutofocus]' })
export class Autofocus {
  constructor() {
    const el = inject<ElementRef<HTMLInputElement>>(ElementRef);
    afterNextRender(() => {
      el.nativeElement.focus();
      console.log('focused', el.nativeElement.name);
    });
  }
}

@Component({
  selector: 'app-root',
  imports: [Autofocus],
  template: `<input name="email" placeholder="Email" appAutofocus />`,
})
export class App {}
focused email

The selector input[appAutofocus] restricts the directive to <input> elements.

Directive checklist

Need Tool
Access the host element inject(ElementRef)
Configurable value input() (optionally aliased to the selector name)
Bind host properties/styles/classes host: { '[prop]': 'expr' }
Listen to host events host: { '(event)': 'handler()' }
Run code after rendering afterNextRender()
Clean up on destroy inject(DestroyRef).onDestroy(...)

Test yourself

What does the selector '[appTooltip]' match?

  1. Elements named <appTooltip>
  2. Elements with the class appTooltip
  3. Elements that have an appTooltip attribute
  4. Only <input> elements

Where do you declare host event listeners in modern Angular?

  1. In the host property of the decorator, e.g. '(click)': 'onClick()'
  2. In index.html
  3. In a pipe
  4. In angular.json

Does an attribute directive have its own template?

  1. Yes, always
  2. No — it adds behaviour to the element it is placed on
  3. Only if it uses signals
  4. Only structural directives lack templates