Can you create a custom directive in Angular?
Yes, you can create a custom directive in Angular.
Principle:
- A class is created with the
@Directivedecorator. - A selector is specified, through which the directive will be applied to an element.
- Inside the class you can control the element via
ElementRef, add styles viaRenderer2, 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 readyPremium
A concise answer to help you respond confidently on this topic during an interview.