0
0
AngularConceptBeginner · 3 min read

What is Attribute Directive in Angular: Simple Explanation and Example

In Angular, an attribute directive changes the appearance or behavior of an existing HTML element, component, or another directive. It works by adding or modifying the element's attributes without creating a new element in the DOM.
⚙️

How It Works

Think of an attribute directive like a sticker you put on a window. The window stays the same, but the sticker can change how it looks or behaves, like tinting the glass or adding a pattern. Similarly, in Angular, attribute directives attach to existing elements and change their style, behavior, or appearance.

Angular detects the directive by its selector, which looks like an attribute on an HTML tag. When Angular renders the page, it runs the directive's code to update the element. This lets you add dynamic effects or logic without changing the element's structure.

💻

Example

This example shows a simple attribute directive that changes the background color of a paragraph when you hover over it.

typescript
import { Directive, ElementRef, HostListener, Renderer2 } from '@angular/core';

@Directive({
  selector: '[appHoverHighlight]'
})
export class HoverHighlightDirective {
  constructor(private el: ElementRef, private renderer: Renderer2) {}

  @HostListener('mouseenter') onMouseEnter() {
    this.renderer.setStyle(this.el.nativeElement, 'background-color', 'yellow');
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.renderer.removeStyle(this.el.nativeElement, 'background-color');
  }
}

// Usage in a component template:
// <p appHoverHighlight>This text will highlight on hover.</p>
Output
When you move your mouse over the paragraph, its background color changes to yellow. When you move the mouse away, the background color returns to normal.
🎯

When to Use

Use attribute directives when you want to change how an existing element looks or behaves without adding new elements. They are perfect for adding effects like highlighting, hiding/showing elements, or changing styles dynamically.

For example, you might use an attribute directive to:

  • Change button colors on user interaction
  • Show or hide elements based on conditions
  • Add animations or style changes on events

Key Points

  • Attribute directives modify existing elements by changing their attributes or behavior.
  • They do not create new elements in the DOM.
  • Use @Directive with a selector that looks like an attribute.
  • Common use cases include styling, hiding/showing, and event-based changes.

Key Takeaways

Attribute directives change the look or behavior of existing elements without adding new ones.
They are applied as attributes on HTML elements using a selector in Angular.
Use attribute directives to add dynamic styles or behaviors like highlighting or hiding elements.
They help keep your templates clean by separating behavior logic from HTML structure.