Directives, Pipes & Templates
Angular Custom Directives
A custom attribute directive is a class with an @Directive decorator that manipulates the element it is placed on. It receives the element through dependency injection and can react to events with @HostListener.
What is Custom Directives in Angular?
A custom attribute directive is a class with an @Directive decorator that manipulates the element it is placed on. It receives the element through dependency injection and can react to events with @HostListener.
Custom Directives example
TypeScript
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[appHighlight]',
standalone: true,
})
export class HighlightDirective {
@Input() appHighlight = '#fef3c7';
constructor(private el: ElementRef<HTMLElement>) {}
@HostListener('mouseenter') onEnter(): void {
this.el.nativeElement.style.backgroundColor = this.appHighlight;
}
@HostListener('mouseleave') onLeave(): void {
this.el.nativeElement.style.backgroundColor = '';
}
}Using it
HTML
<p appHighlight>Hover me</p>
<p [appHighlight]="'#dbeafe'">Custom colour</p>Key points to remember
- Square brackets in the selector mean "matches an element with this attribute".
- Naming the @Input the same as the selector allows the shorthand [appHighlight]="value".
- Prefer Renderer2 over direct nativeElement access for server-side rendering compatibility.
Common mistakes with Custom Directives
- Forgetting to add the directive to the consuming component’s imports array.
- Touching nativeElement in an app that renders on the server, where no DOM exists.
Angular Custom Directives— Interview Questions & FAQs
When should I write a custom directive instead of a component?+
When you want to add behaviour to an existing element rather than render new markup — tooltips, autofocus, permission-based disabling, click-outside detection.
