Sub topic 4
Changing the host element with ElementRef and Renderer2
This chapter assumes you can write a standalone component, know what a decorator is, and have already declared a basic attribute directive with @Directive and an attribute selector. Here you learn how a directive reaches the element it is attached to, which is called the host element, and how to change that element safely.
The host element and why access matters
An attribute directive has no template of its own. Its only target is the element that carries its selector. In <p appHighlight>, the <p> is the host. To change the host, the directive needs a reference to it.
Angular offers two tools for this:
ElementRefis a small wrapper around the native DOM element. ItsnativeElementproperty holds the real element.Renderer2is an abstraction that creates, changes, and removes DOM nodes. It sends the work through the platform's renderer instead of calling browser APIs directly.
Both are provided by dependency injection. In current Angular you request them with the inject() function.
Getting the host with ElementRef
ElementRef is generic. Passing the element type gives you typed access to nativeElement.
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';
}
}The generic argument HTMLElement is a promise you make to the compiler. Angular does not check it. If the directive sits on an <input> and you need value, you would write ElementRef<HTMLInputElement>, and you are responsible for applying the directive only to inputs.
To use the directive, list it in the imports array of a standalone component and add its selector as an attribute.
import { Component } from '@angular/core';
import { HighlightDirective } from './highlight.directive';
@Component({
selector: 'app-demo',
imports: [HighlightDirective],
template: `<p appHighlight>This paragraph is highlighted.</p>`,
})
export class DemoComponent {}If you forget the imports entry, Angular does not apply the directive. Because appHighlight is a plain attribute, the template often compiles without error and the paragraph is simply not highlighted. This is a common cause of "my directive does nothing."
When the host is available
Injected values are ready when the constructor runs, so this.el.nativeElement works there. The element exists at that point, but its bindings and content may not be finished. Reading the element's final size or child nodes in the constructor is unreliable. For that kind of work, use a lifecycle hook or afterNextRender, which are covered in the chapter on injection and cleanup.
Why direct DOM access is a problem
The first example writes to nativeElement.style directly. It works in a browser, and for a small app it may be fine. It has costs:
- Server-side rendering (SSR). On the server there is no browser DOM. Angular substitutes a server implementation of the DOM, and direct calls to browser-only APIs such as
focus()layout reads orwindowaccess may fail or do nothing. - Other platforms. Angular's rendering layer is designed so that the same component code can target different environments. Code that bypasses it ties your directive to a browser.
- Security. Writing to
innerHTMLthroughnativeElementskips Angular's sanitization. This is the biggest practical risk, and the Angular documentation warns against it. - Testability and consistency. Going through one abstraction makes it easier to see where the DOM changes.
The rule of thumb: read from nativeElement if you must, and write through Renderer2 or host bindings.
Changing the host with Renderer2
Renderer2 exposes methods for the common mutations. Every method takes the element as its first argument.
| Method | Purpose |
|---|---|
| `setStyle(el, style, value, flags?)` | Set an inline style |
| `removeStyle(el, style, flags?)` | Remove an inline style |
| `addClass(el, name)` | Add a CSS class |
| `removeClass(el, name)` | Remove a CSS class |
| `setAttribute(el, name, value)` | Set an attribute |
| `removeAttribute(el, name)` | Remove an attribute |
| `setProperty(el, name, value)` | Set a DOM property |
| `createElement`, `appendChild`, `removeChild` | Build and edit nodes |
Style names passed to setStyle use the CSS form, such as background-color, not the camelCase form used on element.style. If you use camelCase, the style may not apply.
The next directive uses Renderer2 together with @HostListener to change the background while the pointer is over the element.
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('mouseenter') registers an event listener on the host and calls the method when the event fires. Event handling gets its own chapter. Here, treat it as the trigger that runs the Renderer2 calls.
Notice that onLeave calls removeStyle, which deletes the inline style. It does not set it to an empty string or a default color. Removing the style lets any stylesheet rule on the element apply again. Setting a fixed value such as white would override the stylesheet and could look wrong on a dark theme.
Flags for important styles
setStyle takes an optional fourth argument for flags from RendererStyleFlags2. Important adds !important, and DashCase tells the renderer that the name is in dash-case. Use Important sparingly, because it is hard to override later.
import { Directive, ElementRef, Renderer2, RendererStyleFlags2, inject } from '@angular/core';
@Directive({
selector: '[appForceRed]',
})
export class ForceRedDirective {
private el = inject<ElementRef<HTMLElement>>(ElementRef);
private renderer = inject(Renderer2);
constructor() {
this.renderer.setStyle(
this.el.nativeElement,
'color',
'red',
RendererStyleFlags2.Important,
);
}
}Classes and attributes
Styles are often the wrong tool. A class lets a stylesheet own the look, and the directive owns only the decision. A directive that toggles a class is easier to theme and easier to override.
import { Directive, ElementRef, Renderer2, inject } from '@angular/core';
@Directive({
selector: '[appRequired]',
})
export class RequiredDirective {
private el = inject<ElementRef<HTMLElement>>(ElementRef);
private renderer = inject(Renderer2);
constructor() {
this.renderer.addClass(this.el.nativeElement, 'is-required');
this.renderer.setAttribute(this.el.nativeElement, 'aria-required', 'true');
}
}The same directive can also set accessibility attributes, as shown with aria-required. A host directive that adds ARIA attributes is a legitimate use of this technique, because it improves every element that carries the selector.
The alternative: host bindings
For values that depend on state, you often do not need Renderer2 at all. The host property of @Directive declares bindings that Angular keeps up to date.
import { Directive, input } from '@angular/core';
@Directive({
selector: '[appBadge]',
host: {
'[class.badge]': 'true',
'[attr.data-kind]': 'kind()',
},
})
export class BadgeDirective {
kind = input('info');
}Host bindings are declarative, work with signals, and go through Angular's own rendering path, so they are SSR-safe. They are the better choice when the host should always reflect some state. Renderer2 fits better when you act imperatively in response to something, for example adding a class once when an animation ends, or when you create and remove nodes. The next chapter treats host bindings in full.
The diagram shows how the three routes relate.
Choosing between the approaches
| Situation | Preferred tool |
|---|---|
| Style or class that follows state | Host binding |
| One-off or event-driven change | `Renderer2` |
| Creating or removing child nodes | `Renderer2` |
| Reading the element type, value, or size | `ElementRef` |
| Calling `focus()`, `scrollIntoView()`, and similar methods | `ElementRef`, guarded for SSR |
| Setting `innerHTML` | Avoid. Use a template or a sanitized binding |
Edge cases and common errors
- camelCase in setStyle.
setStyle(el, 'backgroundColor', ...)may not apply, so writebackground-color. - Directive not in imports. The attribute is ignored silently. Check the component's
importsfirst. - Wrong host type.
ElementRef<HTMLInputElement>on a<div>compiles and fails at runtime when you readvalue. Constrain the selector, for exampleinput[appTrim], to match the type you claim. - Host is a component. A directive can sit on a component's tag. Then
nativeElementis the component's host element, not an element from its template. You cannot reach inside the component's template this way. - Hosts inside structural blocks. If the host sits inside
@if, the directive is created and destroyed with the block. Anything you added to the host goes away with it, but anything you attached elsewhere, such as listeners ondocument, does not. Clean those up. - Mixing both approaches. If a host binding and
Renderer2both set the same style, the last writer wins on each change detection pass, and the result looks random. Pick one owner for each property. - Server-side rendering. Guard browser-only calls. Prefer
afterNextRenderfor code that needs a real browser, since it runs only there.
Putting it together
A directive can combine all three tools. This one trims whitespace from an input when it loses focus. It reads the value from nativeElement, because Renderer2 has no read method, and it writes through setProperty.
import { Directive, ElementRef, HostListener, Renderer2, inject } from '@angular/core';
@Directive({
selector: 'input[appTrim]',
})
export class TrimDirective {
private el = inject<ElementRef<HTMLInputElement>>(ElementRef);
private renderer = inject(Renderer2);
@HostListener('blur')
onBlur() {
const input = this.el.nativeElement;
this.renderer.setProperty(input, 'value', input.value.trim());
}
}The selector input[appTrim] limits the directive to <input> elements, so the HTMLInputElement type is accurate. Note that with Angular forms, changing the DOM value directly does not update the form control. Dispatching an input event or using a ControlValueAccessor is the correct route for forms, which is beyond this chapter.
Exercise
A directive on a <div> calls this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'red') and nothing changes. Give the likely cause and the fix, and explain why removeStyle is usually a better way to undo a style than setting a fixed color.
Show answer
Renderer2.setStyle expects the CSS property name in dash-case, so the call should use 'background-color'. To undo the style, removeStyle deletes the inline declaration, which lets the stylesheet's own value apply again. Setting a fixed color would override the stylesheet and could clash with the page's theme.
Exercise
You want a [appActive] directive to add the class active to its host whenever a boolean input appActive is true. Should you use Renderer2 or a host binding, and what would the host metadata look like?
Show answer
Use a host binding, because the class follows state. With a signal input: host: { '[class.active]': 'appActive()' }, and appActive = input(false) in the class. Angular updates the class on each change, and the code is safe under SSR.