Full answer
A directive is a class that Angular attaches to an element in a template to add behaviour. There are three kinds.
- Components. A component is a directive that also has a template.
- Attribute directives change the look or behaviour of an element, for example
NgClass,NgStyle, or your own[appHighlight]. - Structural directives add or remove elements, such as
*ngIfor*ngFor. These are legacy now, because the built-in control flow (@if,@for) replaced them. You can still write your own structural directive withTemplateRefandViewContainerRef, and it is used in some libraries.
A custom attribute directive needs a @Directive with a selector in square brackets. Modern code uses the host metadata for listeners and bindings instead of @HostListener and @HostBinding, which still work and are common in older code. Angular's style guide recommends host in new code.
The directive gets the element through inject(ElementRef), and uses input() for options. In the example, hovering over a row changes its background colour.
Directives are the right tool when the same behaviour must be added to many different elements, such as a tooltip, auto-focus, or click-outside detection. A component is better if you also need your own markup. More points to know:
- A directive can expose a template reference with
exportAs. Then<div appHighlight #h="appHighlight">gives the template access to the directive instance and its public members. - Directive inputs work like component inputs, including
input.requiredandtransform. Alias the main input to the selector name to allow[appHighlight]="'yellow'". hostDirectiveslets a component or directive attach other directives to its own host and expose chosen inputs. It is a clean way to compose behaviour such as focus handling and tooltips without inheritance.- A structural directive creates or destroys views with
ViewContainerRef.createEmbeddedView(templateRef). The*prefix is only shorthand, so*appUnless="x"becomes anng-templatewith the directive on it. - A directive has no template and cannot have child content of its own. If you need markup, write a component. If you only transform a value for display, write a pipe.
- Directives are standalone by default in current Angular. Add them to the
importsof each component that uses them.
Test a directive with a tiny host component in TestBed: create the host, dispatch a mouseenter event on the element, and assert the style.
import { Component, Directive, ElementRef, inject, input } from '@angular/core';
@Directive({
selector: '[appHighlight]',
host: {
'(mouseenter)': 'paint(color())',
'(mouseleave)': 'paint(null)',
},
})
export class HighlightDirective {
color = input('lightyellow', { alias: 'appHighlight' });
private el = inject<ElementRef<HTMLElement>>(ElementRef);
paint(value: string | null): void {
this.el.nativeElement.style.backgroundColor = value ?? '';
}
}
@Component({
selector: 'app-student-list',
imports: [HighlightDirective],
template: `
<ul>
<li appHighlight="lightyellow">Asha</li>
<li appHighlight="lightblue">Imran</li>
</ul>
`,
})
export class StudentListComponent {}Angular 20.3. Use it as `<li appHighlight="lightyellow">Asha</li>` in a component that imports HighlightDirective.
Key points
- Three kinds: components, attribute directives, structural directives.
- `@Directive({ selector: '[appName]' })` creates an attribute directive.
- Use `host: { '(event)': 'handler()', '[class.x]': 'expr' }` for listeners and bindings.
- Built-in structural directives are legacy; control flow blocks replace them.
Common mistakes
- Changing styles by reaching into the DOM through `document.querySelector` instead of the element Angular gives you.
- Forgetting to add the directive to the `imports` of the component that uses it.
- Choosing a selector that clashes with a native attribute or another library.
Follow-ups
- When would you write a directive instead of a component?
- How do you apply a directive to an element conditionally?
- What does the `host` property replace?
Tips
- Prefix selectors (`app`) and say why: it avoids collisions with HTML and libraries.
- Mention `host` metadata over `@HostListener` and say the decorators are still valid.
- Keep the demo short. Highlight on hover is enough.
Evaluation rubric
- Lists three kinds of directives.
- Writes a working attribute directive with host listeners.
- Knows structural directives are now legacy.