Creating Custom Directives in Angular 🎯

beginner
14 min

Creating Custom Directives in Angular 🎯

Welcome to our comprehensive guide on creating custom directives in Angular! In this tutorial, we'll walk you through the process of creating and using custom directives, explaining why they are essential for structuring and enhancing your Angular applications.

What are Directives in Angular? 📝

Directives are one of the fundamental building blocks of Angular applications. They allow you to extend HTML's capabilities, enabling you to create custom behavior, data-binding, and more. There are three types of directives in Angular:

  1. Component: A directive that includes HTML, CSS, and TypeScript, encapsulating a piece of the application.
  2. Structural: These directives change the layout by adding, removing, or modifying elements in the DOM. Examples include *ngFor and *ngIf.
  3. Attribute: These directives change the behavior of an existing HTML element. We will focus on creating attribute directives in this tutorial.

Creating a Custom Attribute Directive 💡

Let's create a custom attribute directive that highlights text when a mouse hovers over it.

Step 1: Create a new Directive 🎯

First, let's create the directive in a new file called highlight.directive.ts:

typescript
import { Directive, HostListener, ElementRef } from '@angular/core'; @Directive({ selector: '[appHighlight]' }) export class HighlightDirective { constructor(private elementRef: ElementRef) {} @HostListener('mouseenter') onMouseEnter() { this.highlight('yellow'); } @HostListener('mouseleave') onMouseLeave() { this.highlight(null); } private highlight(color: string) { this.elementRef.nativeElement.style.backgroundColor = color; } }

In the code above, we've defined a custom directive called appHighlight. The @HostListener decorator allows us to react to events on the host element (the element we've applied the directive to). In this case, we're listening for the mouseenter and mouseleave events to change the background color of the host element.

Step 2: Use the Custom Directive 🎯

Now, let's use our custom directive in a component's template:

html
<h1 appHighlight>Welcome to CodeYourCraft!</h1>

With this, you've created and used a custom attribute directive in Angular!

Quiz Time 📝

Question: What is the purpose of the @HostListener decorator in the custom directive?

A: It's used to listen for events on the component's template B: It's used to listen for events on the directive's host element C: It's used to set the directive's selector

Correct: B

Explanation: The @HostListener decorator allows us to listen for events on the directive's host element, making it possible to change its behavior based on user interactions.


We hope you found this tutorial helpful! As you continue learning Angular, remember to focus on understanding the "why" behind concepts, not just the "how." Happy coding! 💻🎉