Directives: Add Behaviour to Elements
A directive adds behaviour to an existing element. Components are directives with a template; attribute directives have no template - they change the element they sit on.
Components create new elements; directives add behaviour to existing ones. If you find yourself adding the same small behaviour - highlighting on hover, auto-focusing, tracking clicks - to many different elements, a directive lets you write it once and apply it with an attribute. Angular's own class and style bindings work the same way.
Built-in class and style binding
Example
<button [class.active]="isActive()" [class]="{ big: large(), rounded: true }">Save</button>
<div [style.width.%]="progress()" [style.background]="colour()"></div>Your own attribute directive
This directive highlights any element when the mouse is over it. The host setting listens to events and binds styles on the element.
Example
import { Directive, input, signal } from '@angular/core';
@Directive({
selector: '[appHighlight]',
host: {
'(mouseenter)': 'on.set(true)',
'(mouseleave)': 'on.set(false)',
'[style.backgroundColor]': 'on() ? colour() : null',
},
})
export class Highlight {
colour = input('#fef08a', { alias: 'appHighlight' });
on = signal(false);
}Example
// Use it: import Highlight into the component, then
<p appHighlight>Yellow on hover</p>
<p appHighlight="#bbf7d0">Green on hover</p>A useful example: auto-focus
Example
import { Directive, ElementRef, inject, afterNextRender } from '@angular/core';
@Directive({ selector: '[appAutofocus]' })
export class Autofocus {
private el = inject(ElementRef<HTMLElement>);
constructor() {
afterNextRender(() => this.el.nativeElement.focus()); // after the element is on screen
}
}
// <input appAutofocus placeholder="Search">Prefer the
host setting over the older @HostListener and @HostBinding decorators - it is the style the Angular team recommends today.Key points
- Directives add behaviour to elements; components are directives with templates.
- Use [class] and [style] bindings for dynamic styling.
- Write attribute directives with @Directive and the host setting.
📝 Test yourself
1. What does an attribute directive NOT have?
2. What does selector: '[appHighlight]' match?
3. Fill in the decorator for an attribute directive:
@({ selector: '[appAutofocus]' })
