Angulat directives are powerful tools that extend HTML’s capabilities by allowing you to create custom, reusable elements and attributes.
Types of Angular Directives
Angular provide three main types of directives:
1. Component Directives
Component are directives with a template. They’re the most common type of directive and form the building blocks of Angular applications. Every Angular component is technically a directive.
2. Structural Directives
These directives alter the DOM layout by adding and removing DOM elements. Common example include:
*ngIffor conditional rendering*ngForfor iterating over lists*ngSwitchfor switching between multiple elements
3. Attribute Directives
These directives change the appearance or behavior of an element. Examples include:
ngClassfor adding/removing CSS classesngStylefor adding inline stylesngModelfor two-way data binding
Creating a Custom Directive
let’s create a highlight directive that changes the background color of an element when hovered:
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
@Input() highlightColor: string = 'yellow';
private defaultColor: string = 'transparent';
constructor(private el: ElementRef) {}
@HostListener('mouseenter') onMouseEnter() {
this.highlight(this.highlightColor);
}
@HostListener('mouseleave') onMouseLeave() {
this.highlight(this.defaultColor);
}
private highlight(color: string) {
this.el.nativeElement.style.backgroundColor = color;
}
}
Usage in template:
<p appHighlight highlightColor="lightblue">
Hover over this text to see the highlight effect
</p>
Complex Structural Directive Example
Now, let’s create a custom structural directive that repeats an element a specified number of times:
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[appRepeatTimes]'
})
export class RepeatTimesDirective {
constructor(
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef
) {}
@Input() set appRepeatTimes(times: number) {
this.viewContainer.clear();
for (let i = 0; i < times; i++) {
this.viewContainer.createEmbeddedView(this.templateRef, {
index: i,
total: times
});
}
}
}
Usage in template:
<div *appRepeatTimes="3">
This content will be repeated 3 times
</div>
Registering Directives
Don’t forget to declare your directives in your Angular module:
@NgModule({
declarations: [
HighlightDirective,
RepeatTimesDirective
],
// ... other module properties
})
export class AppModule { }