Skip to main content

What is an attribute directive?

An attribute directive in Angular is a directive that changes the appearance or behavior of an existing element without creating or removing it in the DOM.

Details

  1. Applied as an attribute of an HTML tag, for example [ngClass] or [ngStyle].
  2. Controls the styles, classes, events or other properties of the element.
  3. Does not affect the DOM structure: the element stays in place.

Example of a custom attribute directive:

typescript
import { Directive, ElementRef, Renderer2 } from '@angular/core'; @Directive({ selector: '[appHighlight]' }) export class HighlightDirective { constructor(el: ElementRef, renderer: Renderer2) { renderer.setStyle(el.nativeElement, 'background-color', 'yellow'); } }

Usage in a template:

html
<p appHighlight>Text with a yellow background</p>

Conclusion: attribute directives let you change element properties and behavior without removing or creating them.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.