Problem Statement
What is a directive in Angular and when would you create one?
Explanation
A directive is a class with the @Directive (or @Component) decorator that adds behavior to DOM elements. Use one when multiple components need the same DOM behavior (e.g., hover styles, auto-focus, lazy images). Components are directives with a template; attribute/structural directives change appearance or layout without their own view.
Code Solution
SolutionRead Only
import { Directive, ElementRef, HostListener, Renderer2 } from '@angular/core';
@Directive({ selector: '[appHoverBg]' })
export class HoverBgDirective {
constructor(private el: ElementRef, private r: Renderer2) {}
@HostListener('mouseenter') onEnter(){ this.r.setStyle(this.el.nativeElement,'background','#fff3cd'); }
@HostListener('mouseleave') onLeave(){ this.r.removeStyle(this.el.nativeElement,'background'); }
}