Angular's Directive

Gagan BNGagan BN
2 min read

Understanding Angular Directives

In Angular, directives are essential tools for adding extra functionality to elements. They are implemented using the @Directive decorator. For instance, Angular provides built-in directives like ngIf for conditionally rendering elements and ngFor for iterating over arrays and displaying data.

Creating Custom Directives

You can also create custom directives in Angular to tailor behavior according to your needs. Let's illustrate this with an example:
creating an ElementHighlighter directive.

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

@Directive({  
     selector: '[appHighlighterDirective]'                                                                                                                   selector: '[appHighlighterDirective]' 
}) 
export class HighlighterDirective { 
    constructor(private el: ElementRef) {}

    @HostListener('mouseenter') onMouseEnter() { 
        this.highlight('yellow'); 
    }

    @HostListener('mouseleave') onMouseLeave() { 
        this.highlight(null); 
    }

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

Explanation

  • We define our custom directive HighlighterDirective using the @Directive decorator.

  • The directive listens to the mouse enter and leave events using @HostListener.

  • When the mouse enters an element, it changes the background color to yellow, and when it leaves, it restores the original color.

  • We achieve this by accessing the element's native element through ElementRef and manipulating its backgroundColor property.

How to use

Here's an example of how you can use the HighlighterDirective in an Angular component template:

<!-- app.component.html -->

<div appHighlighterDirective>
  Hover over me to see the highlight effect!
</div>

Conclusion

Directives are powerful tools in Angular for extending HTML functionality. By understanding how to create custom directives, you can enhance your Angular applications with tailored behavior to meet specific requirements.

0
Subscribe to my newsletter

Read articles from Gagan BN directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Gagan BN
Gagan BN