Directives & Pipes
Building Custom Directives
@Directive Decorator
💡 Custom directive apna khud ka "reusable superpower" banana hai — jaise ek naya makeup technique invent karna jo baar-baar kisi bhi element par apply kar sako, bina baar-baar same code likhe.
@Directive decorator se custom directive banate hain — @Component jaisa hi hai, lekin koi template nahi (sirf BEHAVIOR add karta hai existing elements par). ElementRef se DOM element access karte hain, HostListener se events sunte hain.
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private el: ElementRef) { }
@HostListener('mouseenter')
onMouseEnter() {
this.el.nativeElement.style.backgroundColor = 'yellow';
}
@HostListener('mouseleave')
onMouseLeave() {
this.el.nativeElement.style.backgroundColor = '';
}
}
// Use karna:
// <p appHighlight>Hover over me!</p>🔧
Custom directive apna khud ka "reusable superpower" banana hai — jaise ek naya makeup technique invent karna jo baar-baar kisi bhi element par apply kar sako, bina baar-baar same code likhe.
1 / 2
⚡ झट से Recap
- @Directive = custom directive banane ka decorator
- ElementRef = DOM element access karna
- @HostListener = events sunna (mouseenter, click, etc.)
इस page में (2 subtopics)
Custom directives @Input() bhi le sakte hain — directive ka behavior CONFIGURABLE banate hain, jaise highlight color ko parameter se control karna.
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
@Input() appHighlight = 'yellow'; // directive selector jaisa hi naam — convention
constructor(private el: ElementRef) { }
@HostListener('mouseenter')
onMouseEnter() {
this.el.nativeElement.style.backgroundColor = this.appHighlight;
}
}
// Use: <p [appHighlight]="'lightblue'">Custom color hover</p>Tip: @Input() ka naam directive selector jaisा hi rakhna (jaise appHighlight directive mein @Input() appHighlight) ek Angular convention hai — "shorthand" property binding allow karta hai bina extra attribute ke.
Directly ElementRef.nativeElement manipulate karna (jaise .style.x = y) SERVER-SIDE rendering (SSR) mein FAIL ho sakta hai (jaha DOM exist hi nahi karta). Renderer2 ek SAFE, platform-agnostic API deta hai DOM changes ke liye.
import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';
@Directive({ selector: '[appHighlight]' })
export class HighlightDirective {
constructor(private el: ElementRef, private renderer: Renderer2) { }
@HostListener('mouseenter')
onMouseEnter() {
this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');
}
}Tip: Production-quality directives Renderer2 use karte hain, direct nativeElement manipulation se — SSR compatibility (Angular Universal) aur better security (XSS protection) ke liye best practice hai.