Anna University Plus
Angular Custom Directives: Extending HTML with Attribute and Structural Directives - Printable Version

+- Anna University Plus (https://annauniversityplus.com)
+-- Forum: Front-End JavaScript (https://annauniversityplus.com/Forum-front-end-javascript)
+--- Forum: Angular (https://annauniversityplus.com/Forum-angular)
+--- Thread: Angular Custom Directives: Extending HTML with Attribute and Structural Directives (/angular-custom-directives-extending-html-with-attribute-and-structural-directives)



Angular Custom Directives: Extending HTML with Attribute and Structural Directives - Admin - 03-22-2026

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?


RE: Angular Custom Directives: Extending HTML with Attribute and Structural Directives - indian - 03-25-2026

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.