Sub topic 2
Changing the Host Element with ElementRef and Renderer2
Assume you know TypeScript classes, Angular templates, standalone components, and basic property and event binding. An attribute directive adds behavior to an existing element. It does not create a template of its own.
Accessing and changing the host
The host element is the element that carries the directive's selector. Inject ElementRef to access it. Use Renderer2 when changing styles, properties, or classes because it keeps DOM operations inside Angular's rendering abstraction.
import {
Directive,
ElementRef,
HostListener,
Renderer2,
inject,
} from '@angular/core';
@Directive({
selector: '[appHover]',
})
export class HoverDirective {
private element = inject<ElementRef<HTMLElement>>(ElementRef);
private renderer = inject(Renderer2);
@HostListener('mouseenter')
onEnter() {
this.renderer.setStyle(
this.element.nativeElement,
'background-color',
'lightgray',
);
}
@HostListener('mouseleave')
onLeave() {
this.renderer.removeStyle(
this.element.nativeElement,
'background-color',
);
}
}@HostListener connects a method to an event from the host. The host metadata property provides another way to declare bindings:
@Directive({
selector: '[appHighlight]',
host: {
'[style.backgroundColor]': 'active() ? (color() || "yellow") : null',
'(mouseenter)': 'active.set(true)',
'(mouseleave)': 'active.set(false)',
},
})
export class HighlightDirective {
color = input('', { alias: 'appHighlight' });
active = signal(false);
}Here, the directive's input shares the selector name. Therefore, both forms are valid:
<p appHighlight>Default yellow on hover</p>
<p appHighlight="lightblue">Light blue on hover</p>Emitting events
A directive can expose an output so its host component can respond to behavior discovered by the directive.
import { Directive, ElementRef, inject, output } from '@angular/core';
@Directive({
selector: '[appClickOutside]',
host: {
'(document:click)': 'onDocumentClick($event)',
},
})
export class ClickOutsideDirective {
private element = inject<ElementRef<HTMLElement>>(ElementRef);
clickOutside = output<MouseEvent>();
onDocumentClick(event: MouseEvent) {
if (!this.element.nativeElement.contains(event.target as Node)) {
this.clickOutside.emit(event);
}
}
}A parent template can listen with normal event-binding syntax:
<aside appClickOutside (clickOutside)="closeMenu()">
Menu content
</aside>Exercise
Which API should you choose for a directive that sets a style from a signal and updates automatically when the signal changes?
Show answer
Use a host style binding. Use Renderer2 when the change must happen imperatively in response to an operation or event.