-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDirectives-Examples
421 lines (334 loc) · 10.5 KB
/
Directives-Examples
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
// Example 1: Custom Highlight Directive
// app.ts
import { Component, Directive, Input, HostListener, HostBinding, ElementRef, Renderer2, TemplateRef, ViewContainerRef, OnInit, OnDestroy } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { FormsModule, NG_VALIDATORS, Validator, AbstractControl, ValidationErrors } from '@angular/forms';
import { Subscription, fromEvent } from 'rxjs';
// Custom Highlight Directive
@Directive({
selector: '[appHighlight]',
standalone: true
})
export class HighlightDirective {
constructor(private el: ElementRef, private renderer: Renderer2) {}
@HostListener('mouseenter') onMouseEnter() {
this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');
}
@HostListener('mouseleave') onMouseLeave() {
this.renderer.removeStyle(this.el.nativeElement, 'backgroundColor');
}
}
// Example 2: Basic Custom Directive
@Directive({
selector: '[appCustomDirective]',
standalone: true
})
export class CustomDirective implements OnInit {
ngOnInit() {
console.log('Custom directive initialized');
}
}
// Example 3: Text Color Directive with ElementRef
@Directive({
selector: '[appTextColor]',
standalone: true
})
export class TextColorDirective {
constructor(private el: ElementRef) {
this.el.nativeElement.style.color = 'blue';
}
}
// Example 4: Font Size Directive with Renderer2
@Directive({
selector: '[appFontSize]',
standalone: true
})
export class FontSizeDirective {
constructor(private el: ElementRef, private renderer: Renderer2) {
this.renderer.setStyle(this.el.nativeElement, 'font-size', '20px');
}
}
// Example 5: Click Event Listener Directive
@Directive({
selector: '[appClick]',
standalone: true
})
export class ClickDirective {
constructor(private el: ElementRef) {}
@HostListener('click') onClick() {
alert('Element clicked!');
}
}
// Example 6: Hover Highlight Directive
@Directive({
selector: '[appHoverHighlight]',
standalone: true
})
export class HoverHighlightDirective {
constructor(private el: ElementRef, private renderer: Renderer2) {}
@HostListener('mouseenter') onMouseEnter() {
this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'lightgray');
}
@HostListener('mouseleave') onMouseLeave() {
this.renderer.removeStyle(this.el.nativeElement, 'backgroundColor');
}
}
// Example 7: Border Toggle Directive with HostBinding
@Directive({
selector: '[appBorderToggle]',
standalone: true
})
export class BorderToggleDirective {
@HostBinding('class.border-highlight') isHighlighted = false;
@HostListener('mouseover') onMouseOver() {
this.isHighlighted = true;
}
@HostListener('mouseleave') onMouseLeave() {
this.isHighlighted = false;
}
}
// Example 8: Custom Highlight with Input
@Directive({
selector: '[appCustomHighlight]',
standalone: true
})
export class CustomHighlightDirective implements OnInit {
@Input('appCustomHighlight') highlightColor = 'yellow';
constructor(private el: ElementRef, private renderer: Renderer2) {}
ngOnInit() {
this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', this.highlightColor);
}
}
// Example 9: Click Tracker with Output
@Directive({
selector: '[appClickTracker]',
standalone: true
})
export class ClickTrackerDirective {
@HostListener('click') onClick() {
console.log('Tracked click event');
}
}
// Example 10: AutoFocus Directive (Angular 18+)
@Directive({
selector: '[appAutoFocus]',
standalone: true
})
export class AutoFocusDirective implements OnInit {
constructor(private el: ElementRef, private renderer: Renderer2) {}
ngOnInit() {
this.renderer.setAttribute(this.el.nativeElement, 'autofocus', 'true');
}
}
// Example 11: Hydration Directive (Angular 20)
@Directive({
selector: '[appHydrate]',
standalone: true
})
export class HydrateDirective implements OnInit {
constructor(private el: ElementRef) {}
ngOnInit() {
console.log('Hydrated:', this.el.nativeElement);
}
}
// Example 12: Custom Structural Unless Directive
@Directive({
selector: '[appUnless]',
standalone: true
})
export class UnlessDirective {
@Input() set appUnless(condition: boolean) {
if (!condition) {
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
this.viewContainer.clear();
}
}
constructor(private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) {}
}
// Example 13: Event Cleanup Directive
@Directive({
selector: '[appEventCleanup]',
standalone: true
})
export class EventCleanupDirective implements OnDestroy {
private subscription: Subscription;
constructor(private el: ElementRef) {
this.subscription = fromEvent(this.el.nativeElement, 'click').subscribe(() => {
console.log('Clicked');
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
// Example 14: Email Validator Directive for Reactive Forms
@Directive({
selector: '[appEmailValidator]',
standalone: true,
providers: [{ provide: NG_VALIDATORS, useExisting: EmailValidatorDirective, multi: true }]
})
export class EmailValidatorDirective implements Validator {
validate(control: AbstractControl): ValidationErrors | null {
return control.value?.includes('@') ? null : { invalidEmail: true };
}
}
// Example 15: Tooltip Directive
@Directive({
selector: '[appTooltip]',
standalone: true
})
export class TooltipDirective {
@Input() tooltipText: string = '';
constructor(private el: ElementRef, private renderer: Renderer2) {}
@HostListener('mouseenter') onMouseEnter() {
const tooltip = this.renderer.createElement('span');
this.renderer.appendChild(this.el.nativeElement, tooltip);
this.renderer.setProperty(tooltip, 'innerText', this.tooltipText);
this.renderer.setStyle(tooltip, 'position', 'absolute');
this.renderer.setStyle(tooltip, 'background', 'gray');
this.renderer.setStyle(tooltip, 'color', 'white');
this.renderer.setStyle(tooltip, 'padding', '2px 5px');
}
@HostListener('mouseleave') onMouseLeave() {
const tooltip = this.el.nativeElement.querySelector('span');
if (tooltip) this.renderer.removeChild(this.el.nativeElement, tooltip);
}
}
// Main App Component
@Component({
selector: 'app-root',
standalone: true,
imports: [
FormsModule,
HighlightDirective,
CustomDirective,
TextColorDirective,
FontSizeDirective,
ClickDirective,
HoverHighlightDirective,
BorderToggleDirective,
CustomHighlightDirective,
ClickTrackerDirective,
AutoFocusDirective,
HydrateDirective,
UnlessDirective,
EventCleanupDirective,
EmailValidatorDirective,
TooltipDirective
],
template: `
<h1>Angular Directives Demo</h1>
<!-- Example : *ngIf -->
<p *ngIf="isLoggedIn">Welcome, User!</p>
<button (click)="toggleLogin()">Toggle Login</button>
<!-- Example: *ngFor -->
<ul>
<li *ngFor="let item of items; let i = index; trackBy: trackByIndex">
{{ i + 1 }}. {{ item }}
</li>
</ul>
<!-- Example: *ngSwitch -->
<div [ngSwitch]="role">
<p *ngSwitchCase="'admin'">Admin Panel</p>
<p *ngSwitchCase="'user'">User Dashboard</p>
<p *ngSwitchDefault>Select a Role</p>
</div>
<button (click)="role = 'admin'">Admin</button>
<button (click)="role = 'user'">User</button>
<button (click)="role = ''">Reset</button>
<!-- Example: ngClass -->
<p [ngClass]="{'active': isActive, 'disabled': !isActive}">Status</p>
<button (click)="toggle()">Toggle Class</button>
<!-- Example: ngStyle -->
<p [ngStyle]="{'color': isActive ? 'green' : 'red'}">Dynamic Text</p>
<!-- Example: ng-template and ng-container -->
<ng-template #message>
<p>This is a hidden message</p>
</ng-template>
<button (click)="showMessage = true">Show Message</button>
<ng-container *ngIf="showMessage">
<ng-container *ngTemplateOutlet="message"></ng-container>
</ng-container>
<!-- Example: Custom Highlight -->
<p appHighlight>Hover over me to highlight!</p>
<!-- Example: Basic Custom Directive -->
<p appCustomDirective>Text with custom directive</p>
<!-- Example: Text Color -->
<p appTextColor>Blue text via ElementRef</p>
<!-- Example: Font Size -->
<p appFontSize>Large text via Renderer2</p>
<!-- Example: Click Event -->
<button appClick>Click Me for Alert</button>
<!-- Example: Hover Highlight -->
<p appHoverHighlight>Hover for gray background</p>
<!-- Example : Border Toggle -->
<p appBorderToggle>Hover for border effect</p>
<!-- Example: Custom Highlight with Input -->
<p appCustomHighlight="lightblue">Light blue background</p>
<!-- Example: Click Tracker -->
<button appClickTracker>Track This Click</button>
<!-- Example: AutoFocus -->
<input appAutoFocus placeholder="Auto-focused input" />
<!-- Example: @if (Angular 19+) -->
@if (isLoggedIn) {
<p>Welcome back via @if!</p>
} @else {
<p>Please log in via @if</p>
}
<!-- Example: @for (Angular 19+) -->
<ul>
@for (item of items; track item) {
<li>{{ item }}</li>
}
</ul>
<!-- Example: @switch (Angular 19+) -->
@switch (role) {
@case ('admin') {
<p>Admin Dashboard via @switch</p>
}
@case ('user') {
<p>User Dashboard via @switch</p>
}
@default {
<p>Guest View via @switch</p>
}
}
<!-- Example: Hydration -->
<p appHydrate>Hydrated Element</p>
<!-- Example: Custom Unless Directive -->
<p *appUnless="isLoggedIn">You are not logged in (Unless)</p>
<!-- Example: Event Cleanup -->
<button appEventCleanup>Click Me (with cleanup)</button>
<!-- Example: Email Validator -->
<input [(ngModel)]="email" appEmailValidator placeholder="Enter email" />
<p *ngIf="email && !email.includes('@')">Invalid email</p>
<!-- Example: Tooltip -->
<p appTooltip tooltipText="Hello, Tooltip!">Hover for tooltip</p>
`,
styles: [`
.active { background-color: lightgreen; }
.disabled { background-color: lightgray; }
.border-highlight { border: 2px solid red; }
`]
})
export class AppComponent {
isLoggedIn = false;
items = ['Apple', 'Banana', 'Orange'];
role = '';
isActive = false;
showMessage = false;
email = '';
toggleLogin() {
this.isLoggedIn = !this.isLoggedIn;
}
toggle() {
this.isActive = !this.isActive;
}
trackByIndex(index: number) {
return index;
}
}
// Bootstrap the application
bootstrapApplication(AppComponent)
.catch(err => console.error(err));