Angular Custom Directives
In this guide, I will explain what custom directives are in Angular, when to use them, and how to create them with clear examples.
Angular provides powerful tools for building dynamic and reusable directives,
which are one of its core building blocks. While Angular comes with a variety of built-in directives like*ngIf, *ngFor, and ngClass, there are situations where you may need to create your own custom directives to meet specific requirements.Directives
Directives in Angular are classes that can modify the behavior or appearance of elements in the DOM. Angular offers three types of directives:
- Components: These are directives with templates.
- Structural Directives: They change the structure of the DOM, like
*ngIfand*ngFor. - Attribute Directives: They change the appearance or behavior of an existing DOM element, such as
ngClassorngStyle.
You should consider to create a custom directive if:
- You need to encapsulate reusable logic that modifies the DOM.
- You want to add specific behaviors to elements without creating a new component.
- You’re applying dynamic styles, classes, or event listeners repeatedly across your application.
Prerequisites
Angular 20, Npm 10.9.2, Node 22.17.0
Creating New Project
Create a new project by executing the following command:
ng new angular-custom-directives --no-standalone Creating Custom Directives
Creating a custom directive in Angular involves these steps:
- Generate the directive using the Angular CLI:
ng generate directive - Implement the logic in the generated directive class.
- Apply the directive to elements in your template.
Directive – highlighting texts or element
I’ll create a directive that highlights an element including texts when the user mouse hovers over it. Generate the directive by executing the following command:
ng generate directive highlight This will generate two files:
highlight.ts
highlight.spec.ts Implement the directive logic by opening highlight.ts and add the following code:
import { Directive, ElementRef, HostListener, input } from '@angular/core';
@Directive({
selector: '[appHighlight]',
standalone: false
})
export class HighlightDirective {
appHighlight = input('');
constructor(private el: ElementRef) {}
@HostListener('mouseenter') onMouseEnter() {
this.highlight(this.appHighlight() || 'red'); //default red
}
@HostListener('mouseleave') onMouseLeave() {
this.highlight(''); // Remove highlight on mouse leave
}
private highlight(color: string) {
this.el.nativeElement.style.backgroundColor = color;
}
} @Directive({ selector: '[appHighlight]' }): This decorator marks the class as an Angular directive and defines its selector. The square brackets [] indicate an attribute directive.
appHighlight = input(''): The input() function adds metadata to the class that makes the directive’s appHighlight property available for binding.
constructor(private el: ElementRef): Injects ElementRef to get a reference to the host DOM element the directive is applied to.
@HostListener('mouseenter') onMouseEnter(): This decorator listens for the mouseenter event on the host element and calls the onMouseEnter method when triggered.
@HostListener('mouseleave') onMouseLeave(): Listens for the mouseleave event.
private highlight(color: string): A helper method to set the background color of the host element.
Usage of the directive
In the app.html file I am going to write some elements with text inside and when you mouse hover over them you will see the the text or element getting highlighted. If you do not specify any color then the default highlighted color will be red.
I have also put some radio buttons to choose the color for highlighting the element with particular color.
<h2>Mouse hover to highlight</h2>
<p appHighlight>Highlight me!</p>
<p appHighlight="blue">Hover over this text to see the highlight effect in blue.</p>
<p appHighlight="yellow">This text will highlight in yellow on mouse hover.</p>
<h3>Pick a highlight color</h3>
<div>
<input type="radio" name="colors" (click)="color='green'">Green
<input type="radio" name="colors" (click)="color='yellow'">Yellow
<input type="radio" name="colors" (click)="color='cyan'">Cyan
</div>
<p [appHighlight]="color">Highlight me!</p> You need to also add a property in the app.ts file in order to use the property [appHighlight]="color" as shown in the above element.
Directive – tooltip
I will create another directive that will show the tooltip text or message when you mouse hover the element.
Create the tooltip directive by executing the following command:
ng generate directive tooltip Implement the logic to show the tooltip in the file tooltip.ts:
import { Directive, Input, ElementRef, Renderer2, HostListener } from '@angular/core';
@Directive({
selector: '[appTooltip]',
standalone: false
})
export class TooltipDirective {
@Input() appTooltip: string = ''; // The tooltip text
private tooltipElement: any;
constructor(private el: ElementRef, private renderer: Renderer2) {}
@HostListener('mouseenter') onMouseEnter() {
this.showTooltip();
}
@HostListener('mouseleave') onMouseLeave() {
this.hideTooltip();
}
private showTooltip() {
this.tooltipElement = this.renderer.createElement('div');
this.renderer.addClass(this.tooltipElement, 'custom-tooltip'); // Add a CSS class for styling
this.renderer.setStyle(this.tooltipElement, 'position', 'absolute');
this.renderer.setStyle(this.tooltipElement, 'background-color', 'black');
this.renderer.setStyle(this.tooltipElement, 'color', 'white');
this.renderer.setStyle(this.tooltipElement, 'padding', '5px');
this.renderer.setStyle(this.tooltipElement, 'border-radius', '3px');
this.renderer.setProperty(this.tooltipElement, 'innerText', this.appTooltip);
// Position the tooltip relative to the hovered element
const hostPos = this.el.nativeElement.getBoundingClientRect();
this.renderer.setStyle(this.tooltipElement, 'top', `${hostPos.bottom + 5}px`);
this.renderer.setStyle(this.tooltipElement, 'left', `${hostPos.left}px`);
this.renderer.appendChild(document.body, this.tooltipElement);
}
private hideTooltip() {
if (this.tooltipElement) {
this.renderer.removeChild(document.body, this.tooltipElement);
this.tooltipElement = null;
}
}
} In the above tooltip directive the style has been applied through the setStyle() function. You can also set the style in the css style sheet file (app.css). For example,
.custom-tooltip {
/*position: absolute;
background-color: #333;
color: #fff;
padding: 5px;
border-radius: 3px;*/
font-size: 12px;
/*top: 100%;
left: 50%;
transform: translateX(-50%);
white-space: nowrap;
z-index: 1000;*/
} To use the tooltip directive, add the following code in the file app.html:
<h2>Tooltips</h2>
<p><span appTooltip="This is a custom tooltip message.">Hover over me!</span></p>
<button appTooltip="This is a tooltip on button!">Hover me</button>
<router-outlet /> Testing Angular Directives
Run the application using the command ng serve and open the application in browser at URL http://localhost:4200, you will see the following page:
Now if no color mentioned then the element will be highlighted with red color.

No comments