Why you should Stop Manipulation DOM with ElementRef in Angular

Manipulating the DOM is easy with Angular. We can directly access the element by using ElementRef provided by @angular/core.

If you manipulate it by using a directive (common use case) — most are likely to use nativeElement directly like this:

import { Directive, ElementRef, OnInit } from '@angular/core';

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective implements OnInit {

  constructor(
    private el: ElementRef
  ) { }

  ngOnInit() {
    this.el.nativeElement.style.color = 'blue';
  }

}

It will correctly change the color of the element. A lot of tutorials demonstrate the use of nativeElement, but is this safe? No, not really.

Why is it so important?

According to Angular docs ElementRef:

Use this API as the last resort when direct access to DOM is needed. Permitting direct access to the DOM can make your application more vulnerable to XSS attacks. Carefully review any use of [_ElementRef_](https://angular.io/api/core/ElementRef) in your code. Use templating and data-binding provided by Angular instead. Alternatively you take a look at [_Renderer_](https://angular.io/api/core/Renderer)which provides API that can safely be used even when direct access to native elements is not supported.

Relying on direct DOM access creates tight coupling between your application and rendering layers which will make it impossible to separate the two and deploy your application into a web worker.

Not good. But, there’s an alternative called Renderer.

Renderer to manipulate the DOM

There are a lot of ways to manipulate the DOM. In this use case, we need to change a CSS property, the color. According to the API, we need to use setStyle like this:

import { Directive, ElementRef, OnInit, Renderer2 } from '@angular/core';

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective implements OnInit {

  constructor(
    private el: ElementRef,
    private renderer: Renderer2
  ) { }

  ngOnInit() {
    // this.el.nativeElement.style.color = 'blue';
    this.renderer.setStyle(this.el.nativeElement, 'color', 'blue');
  }

}

Worked as expected! Renderer is pretty useful for common use cases, and also for complex DOM manipulation.

To target a specific element, you may need to use ViewChild or ContentChild.

In conclusion, stop using ElementRef and use Renderer!

Hope this tutorial will surely help you !

#angular #javascript

Why you should Stop Manipulation DOM with ElementRef in Angular
20.80 GEEK