Custom Directives in Angular
Custom directives in Angular allow you to extend the HTML with your own elements and attributes. This tutorial covers the basics of creating custom directives and how to use them effectively in your Angular applications.
What are Custom Directives?
Custom directives are Angular directives that you create to encapsulate reusable behavior. They can be attribute directives, structural directives, or components.
Creating a Custom Attribute Directive
Here is an example of creating a simple custom attribute directive that changes the background color of an element when hovered over:
import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';
@Directive({
selector: '[appHoverHighlight]'
})
export class HoverHighlightDirective {
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');
}
}
Using the Custom Attribute Directive
<div appHoverHighlight>Hover over me to highlight!</div>
export class AppComponent {}
Creating a Custom Structural Directive
Here is an example of creating a simple custom structural directive that conditionally includes an element based on a condition:
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[appIf]'
})
export class IfDirective {
constructor(private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) {}
@Input() set appIf(condition: boolean) {
if (condition) {
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
this.viewContainer.clear();
}
}
}
Using the Custom Structural Directive
<div *appIf="isVisible">This is conditionally visible</div>
export class AppComponent {
isVisible = true;
}
Creating a Custom Component
Components in Angular are a type of directive with their own template. Here is an example of creating a simple custom component:
import { Component } from '@angular/core';
@Component({
selector: 'app-custom-button',
template: '<button>Click me!</button>',
styles: ['button { color: blue; }']
})
export class CustomButtonComponent {}
Using the Custom Component
<app-custom-button></app-custom-button>
export class AppComponent {}
Key Points
- Custom directives allow you to extend the HTML with your own elements and attributes.
- Attribute directives modify the behavior or appearance of an element.
- Structural directives change the structure of the DOM by adding or removing elements.
- Components are a type of directive with their own template.
Conclusion
Custom directives in Angular are powerful tools for creating reusable and encapsulated behavior. By understanding and using custom directives effectively, you can create more dynamic and maintainable Angular applications. Happy coding!