Welcome to our comprehensive guide on Angular's @Directive Decorator! In this tutorial, we'll explore how to create custom directives using decorators, which are a fundamental part of Angular's powerful feature set. Let's dive in!
Directives are used to extend Angular's built-in DOM elements with new functionality. They can be categorized into three types:
*ngIf, *ngFor, and ngSwitch.A Directive Decorator is a function that modifies the behavior of an existing Angular Directive by adding new features, properties, or selectors. It's a powerful tool for customizing the Angular framework to suit your project needs.
Let's create a simple HighlightDirective that will highlight text in red when a mouse hovers over it.
import { Directive, HostListener, ElementRef } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private el: ElementRef) {}
@HostListener('mouseenter') onMouseEnter() {
this.el.nativeElement.style.backgroundColor = 'red';
}
@HostListener('mouseleave') onMouseLeave() {
this.el.nativeElement.style.backgroundColor = '';
}
}In the above code:
@Directive decorator and provide the selector to specify the DOM elements this Directive should target.ElementRef to get access to the DOM element.@HostListener to listen for events on the host element. In this case, we're listening for the mouseenter and mouseleave events.To use our HighlightDirective, simply add the appHighlight attribute to the HTML element you want to customize:
<div appHighlight>Hover over me!</div>What are the three types of Angular Directives?
Stay tuned for more Angular tutorials, where we'll delve deeper into Directives, Services, Pipes, and other exciting features! 🚀🚀🚀