Table of Contents
In modern web development, providing users with helpful information without cluttering the interface is essential. Custom directives in Angular allow developers to create reusable components that enhance user experience (UX). One popular feature is a tooltip, which displays additional information when users hover over an element. This article guides you through creating a custom tooltip directive in Angular to improve UX.
Understanding Angular Directives
Angular directives are special markers in the DOM that attach specific behavior to elements. They can be built-in, such as ngIf or ngFor, or custom, created by developers to extend functionality. Custom directives are powerful for creating reusable UI components like tooltips, modals, or dropdowns.
Creating the Tooltip Directive
Let’s start by generating a new directive using Angular CLI:
ng generate directive tooltip
This command creates a new directive file, tooltip.directive.ts, where you’ll implement the tooltip logic.
Implementing the Directive
Open tooltip.directive.ts and import necessary modules:
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
Next, define the directive with a selector and initialize variables:
@Directive({
selector: '[appTooltip]'
})
export class TooltipDirective {
@Input() appTooltip: string;
constructor(private el: ElementRef) { }
@HostListener(‘mouseenter’) onMouseEnter() {
this.showTooltip();
}
@HostListener(‘mouseleave’) onMouseLeave() {
this.hideTooltip();
}
private tooltipElement: HTMLElement;
private showTooltip() {
this.tooltipElement = document.createElement(‘span’);
this.tooltipElement.innerText = this.appTooltip;
this.tooltipElement.style.position = ‘absolute’;
this.tooltipElement.style.backgroundColor = ‘#333’;
this.tooltipElement.style.color = ‘#fff’;
this.tooltipElement.style.padding = ‘5px’;
this.tooltipElement.style.borderRadius = ‘4px’;
document.body.appendChild(this.tooltipElement);
const rect = this.el.nativeElement.getBoundingClientRect();
this.tooltipElement.style.top = rect.bottom + ‘px’;
this.tooltipElement.style.left = rect.left + ‘px’;
}
private hideTooltip() {
if (this.tooltipElement) {
document.body.removeChild(this.tooltipElement);
this.tooltipElement = null;
}
}
}
Using the Tooltip Directive
Apply the directive to any element in your component template:
<button [appTooltip]="'Click to submit'">Submit</button>
Ensure you declare the directive in your module’s declarations array. Now, when users hover over the button, a helpful tooltip appears, enhancing UX.
Conclusion
Creating a custom tooltip directive in Angular is straightforward and greatly improves user interaction. By encapsulating tooltip logic into a reusable directive, developers can maintain cleaner code and provide consistent UX across their applications. Experiment with styles and positioning to tailor the tooltips to your design needs.