Popular Posts

July 22, 2024

How would you create a custom directive in Angular

 

Creating a custom directive in Angular allows you to extend the HTML with new behaviors or modify existing behaviors. Custom directives are defined using the @Directive decorator provided by Angular. Here’s a step-by-step guide on how to create a custom directive:

Step-by-Step Guide to Create a Custom Directive:

  1. Create a new Angular project (if you haven't already):

ng new custom-directive-demo
cd custom-directive-demo

2. Generate a new directive using Angular CLI:

ng generate directive highlight


This command creates a new directive file (highlight.directive.ts) and includes it in the module where it was generated (typically app.module.ts).

3. Implement the custom directive logic in highlight.directive.ts:

Here’s an example of a custom directive that changes the background color of an element when the user hovers over it:

// src/app/highlight.directive.ts

import { Directive, ElementRef, HostListener, Input } from '@angular/core';

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  @Input('appHighlight') highlightColor: string = ''; // Input property to set highlight color

  constructor(private el: ElementRef) {}

  @HostListener('mouseenter') onMouseEnter() {
    this.highlight(this.highlightColor || 'yellow'); // Default color if not provided
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.highlight(null); // Remove highlight on mouse leave
  }

  private highlight(color: string | null) {
    this.el.nativeElement.style.backgroundColor = color;
  }
}

Explanation:
  • @Directive({ selector: '[appHighlight]' }): Defines the directive selector as appHighlight, which can be used as an attribute in HTML (<div appHighlight>).
  • @Input('appHighlight') highlightColor: string = '';: Declares an input property highlightColor that allows setting the highlight color from the parent component's template.
  • constructor(private el: ElementRef) {}: Injects ElementRef to access the DOM element the directive is applied to (el.nativeElement).
  • @HostListener('mouseenter') onMouseEnter() { ... }: Listens to the mouseenter event and triggers the highlight method to change the background color.
  • @HostListener('mouseleave') onMouseLeave() { ... }: Listens to the mouseleave event and removes the background color.
  • private highlight(color: string | null) { ... }: Sets the background color of the element to the provided color.

How would you create a custom directive in Angular

  • 4. Use the custom directive in a component's template:

  • <!-- src/app/app.component.html -->


    <div appHighlight highlightColor="lightblue">

      Hover over me to see the highlight effect!

    </div>

    • Here, appHighlight is applied as an attribute directive to the <div> element.
    • highlightColor is used to pass a value (lightblue) to the directive's input property (highlightColor).
  • 5. Include the custom directive (HighlightDirective) in the module where it will be used (typically AppModule):

    // src/app/app.module.ts


    import { NgModule } from '@angular/core';

    import { BrowserModule } from '@angular/platform-browser';


    import { AppComponent } from './app.component';

    import { HighlightDirective } from './highlight.directive'; // Import the directive


    @NgModule({

      declarations: [

        AppComponent,

        HighlightDirective // Include the directive in declarations

      ],

      imports: [

        BrowserModule

      ],

      providers: [],

      bootstrap: [AppComponent]

    })

    export class AppModule { }

  • 6. Serve and view the Angular application:

  • ng serve --open

  • Navigate to http://localhost:4200 in your browser to see the application running.

  • When you hover over the <div> element in the example, it should change its background color to lightblue due to the custom directive (HighlightDirective) applied.

  • Summary:

    Creating a custom directive in Angular involves defining a TypeScript class decorated with @Directive, implementing the desired behavior using @HostListener for events, and optionally using @Input to accept data from the parent component. Custom directives enhance Angular applications by enabling reusable and customizable behavior across elements, providing a powerful way to extend HTML with Angular's features.

  • No comments:
    Write comments