Angular course · Module 14: Advanced Patterns
Custom Directives
In this lesson3
Directives are like secret ninja techniques - they extend the capabilities of elements.
Attribute Directive
@Directive({
selector: '[appHighlight]',
standalone: true
})
export class HighlightDirective {
private el = inject(ElementRef);
private renderer = inject(Renderer2);
// Input with alias (directive name)
@Input() appHighlight = '#ffff00';
@Input() highlightOnFocus = false;
@HostListener('mouseenter')
onMouseEnter(): void {
this.setBackground(this.appHighlight);
}
@HostListener('mouseleave')
onMouseLeave(): void {
this.setBackground('');
}
@HostListener('focus')
onFocus(): void {
if (this.highlightOnFocus) {
this.setBackground(this.appHighlight);
}
}
private setBackground(color: string): void {
this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', color);
}
}
// Usage
<p appHighlight="#ffff00">Yellow highlight</p> <!-- a bare <p appHighlight> would pass an empty string to the input, not its default value -->
<p [appHighlight]="'#c41e3a'">Red highlight</p>
<input [appHighlight]="'#90EE90'" [highlightOnFocus]="true">Structural Directive
@Directive({
selector: '[appRepeat]',
standalone: true
})
export class RepeatDirective {
private templateRef = inject(TemplateRef<any>);
private viewContainer = inject(ViewContainerRef);
@Input() set appRepeat(count: number) {
this.viewContainer.clear();
for (let i = 0; i < count; i++) {
this.viewContainer.createEmbeddedView(this.templateRef, {
$implicit: i, // Available as let-i
index: i,
first: i === 0,
last: i === count - 1
});
}
}
}
// Usage
<div *appRepeat="5; let i; let isFirst = first">
Element {{ i }} {{ isFirst ? '(first)' : '' }}
</div>Permission Directive
@Directive({
selector: '[appHasPermission]',
standalone: true
})
export class HasPermissionDirective {
private templateRef = inject(TemplateRef<any>);
private viewContainer = inject(ViewContainerRef);
private authService = inject(AuthService);
private hasView = false;
@Input() set appHasPermission(permission: string | string[]) {
const permissions = Array.isArray(permission) ? permission : [permission];
const hasPermission = this.authService.hasAnyPermission(permissions);
if (hasPermission && !this.hasView) {
this.viewContainer.createEmbeddedView(this.templateRef);
this.hasView = true;
} else if (!hasPermission && this.hasView) {
this.viewContainer.clear();
this.hasView = false;
}
}
}
// Usage
<button *appHasPermission="'admin'">Admin Panel</button>
<div *appHasPermission="['editor', 'admin']">Edit Content</div>Code for this lesson: src/app/app.component.ts
import { Component, signal, Directive, ElementRef, Renderer2, inject, HostListener, input, Pipe, PipeTransform } from '@angular/core';
import { CommonModule } from '@angular/common';
// Custom Directive - Highlight
@Directive({
selector: '[appHighlight]',
standalone: true
})
export class HighlightDirective {
private el = inject(ElementRef);
private renderer = inject(Renderer2);
appHighlight = input('#ffff00');
@HostListener('mouseenter')
onMouseEnter(): void {
this.setBackground(this.appHighlight());
}
@HostListener('mouseleave')
onMouseLeave(): void {
this.setBackground('');
}
private setBackground(color: string): void {
this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', color);
this.renderer.setStyle(this.el.nativeElement, 'transition', 'background-color 0.3s');
}
}
// Custom Pipe - Truncate
@Pipe({
name: 'truncate',
standalone: true
})
export class TruncatePipe implements PipeTransform {
transform(value: string, limit = 50, trail = '...'): string {
if (!value) return '';
if (value.length <= limit) return value;
return value.substring(0, limit) + trail;
}
}
// Custom Pipe - Relative Time
@Pipe({
name: 'relativeTime',
standalone: true
})
export class RelativeTimePipe implements PipeTransform {
transform(value: Date | string | number): string {
const date = new Date(value);
const now = new Date();
const diffMs = now.getTime() - date.getTime();
const diffMins = Math.floor(diffMs / 60000);
const diffHours = Math.floor(diffMs / 3600000);
const diffDays = Math.floor(diffMs / 86400000);
if (diffMins < 1) return 'just now';
if (diffMins < 60) return `${diffMins} min ago`;
if (diffHours < 24) return `${diffHours} hours ago`;
if (diffDays < 7) return `${diffDays} days ago`;
return date.toLocaleDateString('en-US');
}
}
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule, HighlightDirective, TruncatePipe, RelativeTimePipe],
template: `
<div class="advanced-dojo">
<h1>Custom Directives and Pipes</h1>
<section>
<h2>Custom Directive - Highlight</h2>
<div class="directive-demo">
<p appHighlight>
Hover over me! (default color: yellow)
</p>
<p [appHighlight]="'#e94560'">
Hover over me! (color: pink)
</p>
<p [appHighlight]="'#2ecc71'">
Hover over me! (color: green)
</p>
</div>
<pre><code>{{ directiveCode }}</code></pre>
</section>
<section>
<h2>Custom Pipe - Truncate</h2>
<div class="pipe-demo">
<p><strong>Original text:</strong></p>
<p class="original">{{ longText }}</p>
<p><strong>Truncated (50 chars):</strong></p>
<p class="truncated">{{ longText | truncate }}</p>
<p><strong>Truncated (30 chars, ">>>"):</strong></p>
<p class="truncated">{{ longText | truncate:30:'>>>' }}</p>
</div>
</section>
<section>
<h2>⏰ Custom Pipe - Relative Time</h2>
<div class="time-demo">
@for (event of events(); track event.id) {
<div class="event-item">
<span class="event-name">{{ event.name }}</span>
<span class="event-time">{{ event.date | relativeTime }}</span>
</div>
}
</div>
</section>
<section>
<h2>Pipes Code</h2>
<pre><code>{{ pipeCode }}</code></pre>
</section>
</div>
`,
styles: [`
.advanced-dojo {
font-family: 'Segoe UI', sans-serif;
padding: 20px;
background: linear-gradient(135deg, #2d1b4e 0%, #1a1a2e 100%);
min-height: 100vh;
color: #eee;
}
h1 {
text-align: center;
color: #a855f7;
}
h2 {
color: #a855f7;
border-bottom: 2px solid #a855f7;
padding-bottom: 10px;
}
section {
background: rgba(255,255,255,0.05);
border-radius: 10px;
padding: 20px;
margin: 20px 0;
}
.directive-demo p {
padding: 15px;
margin: 10px 0;
border-radius: 8px;
background: rgba(0,0,0,0.3);
cursor: pointer;
transition: all 0.3s;
}
.pipe-demo .original {
background: rgba(0,0,0,0.3);
padding: 15px;
border-radius: 8px;
}
.pipe-demo .truncated {
background: rgba(168, 85, 247, 0.2);
border: 1px solid #a855f7;
padding: 15px;
border-radius: 8px;
}
.time-demo {
display: flex;
flex-direction: column;
gap: 10px;
}
.event-item {
display: flex;
justify-content: space-between;
padding: 12px;
background: rgba(0,0,0,0.3);
border-radius: 8px;
border-left: 4px solid #a855f7;
}
.event-name {
font-weight: bold;
}
.event-time {
color: #a855f7;
}
pre {
background: #0a0a15;
padding: 15px;
border-radius: 8px;
overflow-x: auto;
border-left: 4px solid #a855f7;
}
code {
color: #e6e6e6;
font-family: 'Fira Code', monospace;
font-size: 0.85em;
}
`]
})
export class AppComponent {
longText = 'Miyamoto Musashi was a legendary Japanese swordsman, philosopher, and artist. He wrote "The Book of Five Rings", a classic text on strategy and martial arts.';
events = signal([
{ id: 1, name: 'Morning training', date: new Date() },
{ id: 2, name: 'Meditation', date: new Date(Date.now() - 30 * 60000) },
{ id: 3, name: 'Training fight', date: new Date(Date.now() - 3 * 3600000) },
{ id: 4, name: 'Meeting with the master', date: new Date(Date.now() - 2 * 86400000) },
{ id: 5, name: 'Tea ceremony', date: new Date(Date.now() - 10 * 86400000) }
]);
directiveCode = `@Directive({
selector: '[appHighlight]',
standalone: true
})
export class HighlightDirective {
private el = inject(ElementRef);
private renderer = inject(Renderer2);
appHighlight = input('#ffff00');
@HostListener('mouseenter')
onMouseEnter(): void {
this.setBackground(this.appHighlight());
}
@HostListener('mouseleave')
onMouseLeave(): void {
this.setBackground('');
}
private setBackground(color: string): void {
this.renderer.setStyle(
this.el.nativeElement,
'backgroundColor',
color
);
}
}
// Usage
<p appHighlight>Default yellow</p>
<p [appHighlight]="'#e94560'">Pink</p>`;
pipeCode = `@Pipe({
name: 'truncate',
standalone: true
})
export class TruncatePipe implements PipeTransform {
transform(value: string, limit = 50, trail = '...'): string {
if (!value) return '';
if (value.length <= limit) return value;
return value.substring(0, limit) + trail;
}
}
// Usage
{{ longText | truncate }}
{{ longText | truncate:30:'>>>' }}
@Pipe({
name: 'relativeTime',
standalone: true
})
export class RelativeTimePipe implements PipeTransform {
transform(value: Date | string | number): string {
const date = new Date(value);
const now = new Date();
const diffMs = now.getTime() - date.getTime();
const diffMins = Math.floor(diffMs / 60000);
if (diffMins < 1) return 'just now';
if (diffMins < 60) return \`\${diffMins} min ago\`;
// ...
}
}
// Usage
{{ event.date | relativeTime }}`;
}Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What do we need to inject to create a custom structural directive?
2. A directive that changes an element's background on mouse hover (appHighlight) is an example of:
These are 2 of 3 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Horizontal ordering
Arrange the decorator that listens for the mouseenter event on the host element (one line, left to right):
- Code editor
Complete the highlight directive that changes the background on hover.
- Vertical ordering
Order the lines of an attribute directive definition (top to bottom):