Skip to main content

Can you create a custom directive in Angular?

Yes, you can create a custom directive in Angular.

Principle:

  1. A class is created with the @Directive decorator.
  2. A selector is specified, through which the directive will be applied to an element.
  3. Inside the class you can control the element via ElementRef, add styles via Renderer2, listen for events and so on.

Example of a simple 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: a custom directive lets you extend the functionality of elements and create reusable behavior.

Short Answer

Interview ready
Premium

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