In this section, we will explore custom directives in Angular. Directives are a powerful feature in Angular that allow you to extend the HTML vocabulary and create reusable components. Custom directives can be used to manipulate the DOM, apply styles, and add behavior to elements.

Key Concepts

  1. What are Directives?

    • Directives are classes that add additional behavior to elements in your Angular applications.
    • There are three types of directives in Angular:
      • Component Directives: Directives with a template.
      • Structural Directives: Directives that change the DOM layout by adding and removing DOM elements (e.g., *ngIf, *ngFor).
      • Attribute Directives: Directives that change the appearance or behavior of an element, component, or another directive (e.g., ngClass, ngStyle).
  2. Creating a Custom Directive

    • Custom directives are typically attribute directives.
    • They are created using the @Directive decorator.
  3. Using Custom Directives

    • Custom directives can be applied to elements in your templates.
    • They can interact with the host element and respond to events.

Creating a Custom Directive

Let's create a simple custom directive that changes the background color of an element when it is hovered over.

Step-by-Step Guide

  1. Generate the Directive

    • Use Angular CLI to generate a new directive:
      ng generate directive highlight
      
  2. Implement the Directive

    • Open the generated highlight.directive.ts file and implement the directive logic:
      import { Directive, ElementRef, HostListener, Input } from '@angular/core';
      
      @Directive({
        selector: '[appHighlight]'
      })
      export class HighlightDirective {
        @Input() appHighlight: string;
      
        constructor(private el: ElementRef) {}
      
        @HostListener('mouseenter') onMouseEnter() {
          this.highlight(this.appHighlight || 'yellow');
        }
      
        @HostListener('mouseleave') onMouseLeave() {
          this.highlight(null);
        }
      
        private highlight(color: string) {
          this.el.nativeElement.style.backgroundColor = color;
        }
      }
      
  3. Use the Directive in a Template

    • Apply the directive to an element in your component template:
      <p appHighlight="lightblue">Hover over this text to see the highlight effect.</p>
      

Explanation

  • @Directive Decorator: Defines the directive and its selector ([appHighlight]).
  • ElementRef: A service that grants direct access to the DOM element.
  • @Input(): Binds the directive's input property to the attribute value.
  • @HostListener(): Listens to events on the host element and triggers the specified methods.
  • highlight() Method: Changes the background color of the host element.

Practical Exercise

Task

Create a custom directive that changes the text color of an element when it is clicked.

Steps

  1. Generate a new directive named textColor.
  2. Implement the directive to change the text color on click.
  3. Use the directive in a component template.

Solution

  1. Generate the Directive

    ng generate directive textColor
    
  2. Implement the Directive

    import { Directive, ElementRef, HostListener, Input } from '@angular/core';
    
    @Directive({
      selector: '[appTextColor]'
    })
    export class TextColorDirective {
      @Input() appTextColor: string;
    
      constructor(private el: ElementRef) {}
    
      @HostListener('click') onClick() {
        this.changeTextColor(this.appTextColor || 'blue');
      }
    
      private changeTextColor(color: string) {
        this.el.nativeElement.style.color = color;
      }
    }
    
  3. Use the Directive in a Template

    <p appTextColor="red">Click this text to change its color to red.</p>
    

Common Mistakes and Tips

  • Forgetting to Declare the Directive: Ensure that the directive is declared in the declarations array of your module.
  • Incorrect Selector: Make sure the selector in the @Directive decorator matches the attribute used in the template.
  • Direct DOM Manipulation: Avoid direct DOM manipulation when possible. Use Angular's built-in methods and services.

Summary

In this section, we learned about custom directives in Angular. We created a custom directive to change the background color of an element on hover and another to change the text color on click. Custom directives are a powerful way to encapsulate and reuse behavior across your application. In the next section, we will explore services and dependency injection in Angular.

© Copyright 2024. All rights reserved