Often when we are using JavaScript techniques inside Angular, we almost forget about the framework’s features. Let’s utilize them.

One of the interesting topics in web development is DOM manipulations. There are many ways to manipulate the DOM in Angular. Let’s use them instead of straight forward JavaScript approaches.

Usually, there are two concepts in DOM Manipulations.

  1. Modifying DOM Elements.
  2. Modifying DOM Structure.

Modifying DOM Elements:

We are familiar with a lot of JavaScript methods that modify the DOM element. Here are some of them:

  1. classList.add()
  2. setAttribute()
  3. style.setProperty()

These all are JavaScript native DOM element methods.

There are multiple ways to modify the DOM elements in Angular. We will discuss almost every method and choose the best among them.

Method: 1

Concepts:

  1. Template reference variables.
  2. ElementRef.
  3. @Viewchild/@Viewchildren.
  4. AfterViewInit.

Definitions:

  1. Template reference — Reference to a particular DOM element.
  2. ElementRef — ElementRef is a class, which consists of all native DOM elements. Using nativeElement object we can access all DOM elements in Angular.
  3. @Viewchild/@Viewchildren — Select child or all children elements from the DOM.
  4. AfterViewInit — One of this Lifecycle hook is called after the Angular component initialized its view.

#angular #dom

How to Use DOM Manipulation properly in Angular
58.05 GEEK