Angular Tutorial: @Directive Decorator 🎯

beginner
22 min

Angular Tutorial: @Directive Decorator 🎯

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!

What are Directives in Angular? 📝

Directives are used to extend Angular's built-in DOM elements with new functionality. They can be categorized into three types:

  1. Component: Comprises a template, CSS, and TypeScript, acting as reusable, self-contained building blocks.
  2. Structural: Changes the DOM structure by adding, removing, or modifying elements. Examples include *ngIf, *ngFor, and ngSwitch.
  3. Attribute: Alters the behavior or appearance of an existing DOM element without changing its structure. We'll focus on Attribute Directives in this tutorial.

What is a Directive Decorator? 💡

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.

Creating a Custom Directive ✅

Let's create a simple HighlightDirective that will highlight text in red when a mouse hovers over it.

typescript
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:

  1. Import necessary modules.
  2. Define the Directive using the @Directive decorator and provide the selector to specify the DOM elements this Directive should target.
  3. Inject the ElementRef to get access to the DOM element.
  4. Use @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:

html
<div appHighlight>Hover over me!</div>

Quiz 📝

Quick Quiz
Question 1 of 1

What are the three types of Angular Directives?

Pro Tip 💡

  • Use Directive Decorators to add custom behavior to existing Angular Directives.
  • Directives can be reused across components, making them a powerful tool for consistency and code reusability.

Stay tuned for more Angular tutorials, where we'll delve deeper into Directives, Services, Pipes, and other exciting features! 🚀🚀🚀