Directives let you change how the page looks or behaves by working directly with the page elements. They help you add or change things on the page easily.
Directive execution and DOM manipulation in Angular
import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core'; @Directive({ selector: '[appHighlight]' }) export class HighlightDirective { constructor(private el: ElementRef, private renderer: Renderer2) {} @HostListener('mouseenter') onMouseEnter() { this.renderer.setStyle(this.el.nativeElement, 'background-color', 'yellow'); } @HostListener('mouseleave') onMouseLeave() { this.renderer.removeStyle(this.el.nativeElement, 'background-color'); } }
Use @Directive to define a directive and set its selector.
Use ElementRef to access the element and Renderer2 to safely change its style or content.
import { Directive, ElementRef, Renderer2 } from '@angular/core'; @Directive({ selector: '[appBold]' }) export class BoldDirective { constructor(el: ElementRef, renderer: Renderer2) { renderer.setStyle(el.nativeElement, 'font-weight', 'bold'); } }
import { Directive, HostListener, ElementRef, Renderer2 } from '@angular/core'; @Directive({ selector: '[appToggle]' }) export class ToggleDirective { private isOn = false; constructor(private el: ElementRef, private renderer: Renderer2) {} @HostListener('click') toggle() { this.isOn = !this.isOn; const color = this.isOn ? 'green' : 'red'; this.renderer.setStyle(this.el.nativeElement, 'color', color); } }
This example shows a directive that highlights the background of a heading when you move the mouse over it and removes the highlight when the mouse leaves.
import { Component } from '@angular/core'; import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core'; @Directive({ selector: '[appHighlight]' }) export class HighlightDirective { constructor(private el: ElementRef, private renderer: Renderer2) {} @HostListener('mouseenter') onMouseEnter() { this.renderer.setStyle(this.el.nativeElement, 'background-color', 'yellow'); } @HostListener('mouseleave') onMouseLeave() { this.renderer.removeStyle(this.el.nativeElement, 'background-color'); } } @Component({ selector: 'app-root', standalone: true, imports: [HighlightDirective], template: `<h2 appHighlight>Hover over me to see highlight</h2>` }) export class AppComponent {}
Always use Renderer2 for DOM changes to keep your app safe and compatible with different platforms.
Use @HostListener to listen to events like clicks or mouse movements on the element.
Directives should be simple and focused on one task for easier reuse and testing.
Directives let you add or change behavior on HTML elements.
Use ElementRef and Renderer2 to safely manipulate the DOM.
Listen to user events with @HostListener to react to actions like clicks or hovers.