Angular Custom Directives: Extending HTML with Attribute and Structural Directives
Angular Custom Directives: Extending HTML with Attribute and Structural Directives
Directives let you extend HTML elements with custom behavior in Angular.
Types of directives:
1. Component directives: Components are directives with templates
2. Attribute directives: Change appearance or behavior of elements
3. Structural directives: Add or remove DOM elements
Creating an attribute directive:
@Directive({ selector: '[appHighlight]' })
export class HighlightDirective {
@HostListener('mouseenter') onMouseEnter() {
this.highlight('yellow');
}
private highlight(color: string) {
this.el.nativeElement.style.backgroundColor = color;
}
}
Useful custom directive ideas:
- Click outside detector for dropdowns
- Auto-focus on form fields
- Infinite scroll loader
- Tooltip directive
- Permission-based element visibility
- Debounce click to prevent double submissions
Structural directive tips:
- Use * syntax for cleaner templates
- Access TemplateRef and ViewContainerRef
- Create custom *ngIf alternatives for specific use cases
What custom directives have been most useful in your projects?
Custom directives are one of Angular's most powerful features for code reuse. Attribute directives like click-outside detectors and debounce-click are incredibly useful across projects. Structural directives with TemplateRef and ViewContainerRef give you full control over DOM manipulation. With standalone directives, sharing them across projects is even easier.