Loading...

Custom Directives in Angular

Custom directives in Angular let you add your own special behaviors to HTML elements. Think of them as ways to make HTML elements do new tricks! We'll create a very simple directive here.

Creating a Simple Highlight Directive

Let's make a directive that changes the background color of an element when you hover your mouse over it.

Step 1: Create the Directive File

Create a file named simple-highlight.directive.ts in your src/app folder.


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

                @Directive({
                    selector: '[appSimpleHighlight]'
                        })
    export class SimpleHighlightDirective {
      constructor(private el: ElementRef, private renderer: Renderer2) {}

                @HostListener('mouseenter') onMouseEnter() {
        this.renderer.setStyle(this.el.nativeElement, 'background-color', 'lightblue');
      }

                @HostListener('mouseleave') onMouseLeave() {
        this.renderer.setStyle(this.el.nativeElement, 'background-color', null);
      }
    }
    

Explanation:

  • @Directive({ selector: '[appSimpleHighlight]' }): This tells Angular to look for elements with the appSimpleHighlight attribute.
  • ElementRef: This gives us a way to access the element.
  • Renderer2: This is the recommended way to manipulate the DOM in Angular. It avoids direct DOM manipulation, which can lead to security vulnerabilities and platform-specific issues.
  • @HostListener('mouseenter'): This listens for when the mouse moves onto the element.
  • @HostListener('mouseleave'): This listens for when the mouse moves away.
  • this.renderer.setStyle(this.el.nativeElement, 'background-color', 'lightblue');: This uses the Renderer2 to set the background color.
  • this.renderer.setStyle(this.el.nativeElement, 'background-color', null);: This clears the background color.

Step 2: Declare the Directive in Your Module

Open app.module.ts and add the directive to the declarations array.


    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { AppComponent } from './app.component';
    import { SimpleHighlightDirective } from './simple-highlight.directive'; // Import

                @NgModule({
                    declarations: [
                      AppComponent,
                      SimpleHighlightDirective // Declare
                    ],
      imports: [
        BrowserModule
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    

Step 3: Use the Directive in Your Template

Open app.component.html and add the appSimpleHighlight attribute to an element.


    <p appSimpleHighlight>Hover over me!</p>
    

Now, when you run your Angular application and hover your mouse over the paragraph, the background color will change to light blue.

If you have any questions, feel free to ask. Thank you for reading!

Thankyou!