Sub topic 4
Changing the host element with ElementRef and Renderer2
This chapter assumes you can declare an attribute directive with @Directive and apply it through the imports array of a standalone component. It also assumes you have used inject() to get a dependency. Here you will learn the two tools a directive uses to change the element it sits on.
What the host element is
The host element is the element that matches the directive's selector. In <p appHighlight>, the <p> is the host. An attribute directive has no template of its own, so changing its host is its whole job. Angular gives you two ways to reach it: ElementRef and Renderer2.
Reading the host with ElementRef
ElementRef is a wrapper around the host's DOM node. Its nativeElement property holds the node itself. Pass the element type as a type argument so nativeElement is typed as HTMLElement instead of any.
import { Directive, ElementRef, inject } from '@angular/core';
@Directive({
selector: '[appHighlight]',
})
export class HighlightDirective {
private el = inject<ElementRef<HTMLElement>>(ElementRef);
constructor() {
this.el.nativeElement.style.backgroundColor = 'yellow';
}
}This works in a browser and is fine for a first experiment. The problem is that it writes to the DOM node directly. Code written this way assumes a real browser DOM. During server-side rendering there may be no such DOM, and direct writes also skip Angular's rendering layer.
Changing the host with Renderer2
Renderer2 is Angular's abstraction over DOM changes. You still use ElementRef to say which element to change, but Renderer2 makes the change. These are its most common methods:
| Method | Effect on the host |
|---|---|
| `setStyle(el, name, value)` | Sets one CSS property |
| `removeStyle(el, name)` | Removes one CSS property |
| `addClass(el, name)` | Adds a CSS class |
| `removeClass(el, name)` | Removes a CSS class |
| `setAttribute(el, name, value)` | Sets an attribute |
| `removeAttribute(el, name)` | Removes an attribute |
The next directive changes the background while the mouse is over the host and restores it afterwards.
import { Directive, ElementRef, HostListener, Renderer2, inject } from '@angular/core';
@Directive({
selector: '[appHover]',
})
export class HoverDirective {
private el = inject<ElementRef<HTMLElement>>(ElementRef);
private renderer = inject(Renderer2);
@HostListener('mouseenter')
onEnter() {
this.renderer.setStyle(this.el.nativeElement, 'background-color', 'lightgray');
}
@HostListener('mouseleave')
onLeave() {
this.renderer.removeStyle(this.el.nativeElement, 'background-color');
}
}@HostListener runs a method when the host emits an event. The next chapter covers host events and bindings in detail. Here it only triggers the style changes.
Notice the pairing. Every change made on mouseenter has a matching undo on mouseleave. Without removeStyle, the gray background would stay after the pointer left.
Using it in a template
Apply the directive as you did in the earlier chapters. Import it into the standalone component and add the attribute:
import { Component } from '@angular/core';
import { HoverDirective } from './hover.directive';
@Component({
selector: 'app-demo',
imports: [HoverDirective],
template: `<p appHover>Hover over this paragraph.</p>`,
})
export class DemoComponent {}Which tool to use
Use Renderer2 for any change you make after the directive has been created, such as in event handlers. Use ElementRef to identify the host, and for read-only needs such as contains() or measuring size. Avoid writing through nativeElement in code that may run on the server.
Common errors
- Forgetting to undo a change. Any style, class, or attribute added in one handler needs a matching removal in the opposite handler.
- Reading inputs in the constructor. The constructor runs before Angular sets input values. Read them in
ngOnInitor in a handler that runs later. - Mixing both approaches. Setting a style through
nativeElementin one method and throughRenderer2in another makes the code hard to follow. PickRenderer2for writes and stay consistent. - Using
anyfor the element. Without theElementRef<HTMLElement>type argument, typos in property names go unnoticed.
Exercise
A directive adds the class "active" to its host in a mouseenter handler using this.renderer.addClass(this.el.nativeElement, 'active'). Which call should the mouseleave handler make, and why is it better to use Renderer2 here than to write this.el.nativeElement.classList.add('active')?
Show answer
The mouseleave handler should call this.renderer.removeClass(this.el.nativeElement, 'active'). Renderer2 is better because it goes through Angular's rendering layer instead of touching the DOM node directly, so the directive does not depend on a browser DOM being present. That matters for server-side rendering.