Skip to main content

What is a directive in Angular?

A directive in Angular is a class that changes the behavior or appearance of DOM elements. It lets you add functionality without creating a new component.

Types of directives

  1. Attribute directives - change the appearance or behavior of existing elements. Examples: ngClass, ngStyle.
  2. Structural directives - change the DOM structure by adding or removing elements. Examples: *ngIf, *ngFor, *ngSwitch.
  3. Component directives - technically also a directive with a template, since a component is a directive with a UI.

Example of an 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'); } }

Conclusion: directives let you add behavior and control the DOM without creating a separate component.

Short Answer

Interview ready
Premium

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