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
- Applied as an attribute of an HTML tag, for example
[ngClass]or[ngStyle]. - Controls the styles, classes, events or other properties of the element.
- 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 readyPremium
A concise answer to help you respond confidently on this topic during an interview.