Skip to main content

What does the @Directive() decorator do?

The @Directive() decorator in Angular indicates that a class is a directive and defines its metadata.

Key features:

  1. selector - the name of the attribute, element or class through which the directive is applied to a DOM element.
  2. Defines the directive's behavior: its interaction with the element, event listeners, styles and so on.
  3. Lets you inject dependencies through the constructor (ElementRef, Renderer2, services).

Example:

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: @Directive() tells Angular that the class will extend or change the behavior of DOM elements.

Short Answer

Interview ready
Premium

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