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);
}@Directiveinstead 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".hostmaps 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, withhoneydewas 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.