Skip to the workspace
Pebellslearn by building
Templates and Directives  ›  Capstone Project

Writing a Custom Directive

Custom Directives 15 minA custom attribute directive is a class with the @Directive decorator and an attribute selector, which uses inputs and host bindings to add reusable behaviour to any element.

angular / Writing a Custom Directive

Explore each scene at your own pace.

01 · The rule

The rule

Writing a Custom Directive

Designers want every clickable thing in Greenhouse, from plant cards to table rows, to tint gently on hover. Copying the same mouse handlers into ten components would be tedious and easy to get wrong. A directive lets you write the behaviour once and attach it to any element with one attribute.

The rule

A directive is a component without a template: it decorates its host.

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

@Directive({
  selector: '[appHighlight]',
  host: {
    '(mouseenter)': 'active.set(true)',
    '(mouseleave)': 'active.set(false)',
    '[style.backgroundColor]': "active() ? highlightColor() : ''",
  },
})
export class Highlight {
  highlightColor = input('honeydew');
  active = signal(false);
}
  • @Directive instead of @Component, and there is no template: the element it sits on, its host, is what it changes.
  • selector: '[appHighlight]' is an attribute selector. The square brackets mean "any element with this attribute".
  • host maps events and bindings onto the host element. Keys in round brackets listen; keys in square brackets bind. They work exactly like template bindings, written from the host's side.
  • input() lets each use pick a colour, with honeydew as the default.

Using it is two steps, import and attach:

@Component({
  selector: 'app-plant-list',
  imports: [Highlight],
  template: `
    <article appHighlight>Fern</article>
    <article appHighlight highlightColor="lightyellow">Cactus</article>
  `,
})
export class PlantList {}

Older code does the same with decorators, @HostListener('mouseenter') and @HostBinding('style.backgroundColor'). Current guidance prefers the host object. When you truly need the raw element, inject(ElementRef) gives it, but binding through host is safer and simpler.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.