← Back to Angular, page 3

angular-0053 · Easy fresher

When is it acceptable to touch the DOM directly in Angular, and what are ElementRef and Renderer2 for?

Prefer template bindings. When you must change the DOM, inject ElementRef to reach the host element and Renderer2 to change it in a platform-safe way. Direct document or window access breaks server rendering, and innerHTML bypasses Angular's protections. Browser-only code belongs in afterNextRender.

Full answer

Angular updates the DOM for you through bindings: [class.active], [style.width.px], [attr.aria-label], @if, and @for. Most of the time this is enough, and it works in every environment.

Sometimes you need more: focusing an input, measuring an element, or wrapping a third-party widget. Then use these tools:

  • ElementRef. inject(ElementRef) gives the host element of a component or directive, through nativeElement. It is a plain object that holds the DOM node.
  • Renderer2. An abstraction for changing the DOM: addClass, setStyle, setAttribute, listen, createElement. On the server it works on Angular's server DOM, and with a custom renderer (for example in tests) it still works. Using nativeElement.style.x also works in the browser, but fails on platforms without a real DOM.
  • viewChild() gives a specific element of your template without a global query.
  • afterNextRender runs browser-only code after the first render, so window, document, localStorage, and layout measurements are safe there.

Things to avoid:

  • document.querySelector inside components. It can find elements from other components and does not work on the server.
  • nativeElement.innerHTML = userText. This skips Angular's sanitization and can allow cross-site scripting. Use [innerHTML] instead, which sanitizes.
  • Reading layout (offsetHeight) in loops while writing styles, which forces repeated layout work.

Angular's own documentation tells you to use ElementRef with care, because direct access makes code harder to test and to run on the server.

typescript
import { Directive, ElementRef, OnDestroy, OnInit, Renderer2, afterNextRender, inject } from '@angular/core';

@Directive({ selector: '[appFocusRing]' })
export class FocusRingDirective implements OnInit, OnDestroy {
  private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
  private readonly renderer = inject(Renderer2);
  private stopFocus?: () => void;
  private stopBlur?: () => void;

  constructor() {
    afterNextRender(() => {
      // Browser only: safe to read layout here.
      console.log('Width:', this.host.nativeElement.offsetWidth);
    });
  }

  ngOnInit(): void {
    const el = this.host.nativeElement;
    this.renderer.setAttribute(el, 'tabindex', '0');
    this.stopFocus = this.renderer.listen(el, 'focus', () => this.renderer.addClass(el, 'ring'));
    this.stopBlur = this.renderer.listen(el, 'blur', () => this.renderer.removeClass(el, 'ring'));
  }

  ngOnDestroy(): void {
    this.stopFocus?.();
    this.stopBlur?.();
  }
}

Angular 20.3. Use as `<p appFocusRing>Click or tab to focus</p>`. The directive adds a class when the element is clicked and removes it on blur.

Key points

  • Use bindings first. Reach for `ElementRef` or `Renderer2` only when bindings cannot do the job.
  • `Renderer2` changes the DOM in a platform-safe way. `ElementRef` gives the host node.
  • Browser-only work goes in `afterNextRender`. Avoid `document.querySelector`.
  • Never assign user text to `innerHTML` through `nativeElement`.

Common mistakes

  • Using `document.getElementById` in a component, which breaks SSR and finds elements from other components.
  • Setting `innerHTML` through `nativeElement` and bypassing sanitization.
  • Querying the DOM in the constructor, before the view exists.

Follow-ups

  • Why does `Renderer2` exist if `nativeElement` works in the browser?
  • How would you measure an element's width safely with SSR enabled?
  • What does `[innerHTML]` do to the HTML you bind?

Tips

  • Start with "bindings first". Interviewers want to hear you avoid DOM access by default.
  • Name the SSR reason, since that is the practical cost.
  • Say what you would use instead for each case: `viewChild`, `afterNextRender`, `[innerHTML]`.

Evaluation rubric

  • Knows the roles of ElementRef and Renderer2.
  • Names SSR and security risks of direct DOM access.
  • Prefers bindings and lifecycle-safe hooks.