How to generate a directive in Angular
Generating Angular directives enables you to create reusable DOM manipulation logic and custom behavior that can be applied across your application. As the creator of CoreUI, a widely used open-source UI library, I’ve generated hundreds of Angular directives for tooltip behavior, input validation, and custom styling logic across enterprise applications. From my expertise, the most efficient approach is to use Angular CLI’s generate directive command. This method creates the proper directive structure with dependency injection and testing files while following Angular best practices.
Use ng generate directive command to create a new Angular directive with proper structure and configuration.
# Generate a basic directive
ng generate directive highlight
# or shortened
ng g d highlight
# Generate directive in specific folder
ng generate directive shared/directives/tooltip
# Verify directive is created
// highlight.directive.ts (generated file)
import { Directive, ElementRef, HostListener, Input, Renderer2 } from '@angular/core'
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
@Input() highlightColor = 'yellow'
constructor(
private el: ElementRef,
private renderer: Renderer2
) {}
@HostListener('mouseenter') onMouseEnter() {
this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', this.highlightColor)
}
@HostListener('mouseleave') onMouseLeave() {
this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'transparent')
}
}
<!-- Usage in component template -->
<p appHighlight>Hover over this text</p>
<p appHighlight highlightColor="lightblue">Custom color highlight</p>
Angular CLI’s ng generate directive command creates the directive class with the @Directive decorator, proper selector, and dependency injection setup. The directive uses @Input for configuration, @HostListener for event handling, and Renderer2 for safe DOM manipulation. Always use Renderer2 instead of direct element access for better security and server-side rendering compatibility.
Best Practice Note:
This is the same approach we use for generating directives in CoreUI Angular components for consistent behavior and DOM manipulation.



