In Angular 8 which one is best preferable way for DOM manipulation

766 views Asked by At

Currently I am learning Angular 8 and I have found that in few articles people are using below kind of code to get html DOM element.

import {AfterViewInit, Component, ElementRef, ViewChild} from '@angular/core';

@Component({
    selector: 'app',
    template: `
        <div #myDiv>Some text</div>
    `,
})
export class AppComponent implements AfterViewInit {
    @ViewChild('myDiv') myDiv: ElementRef;

    ngAfterViewInit() {
        console.log(this.myDiv.nativeElement.innerHTML);
    }
}

but compared to above code we can get html DOM element using document.getElementById("myDiv") as below.

import {AfterViewInit, Component, ElementRef, ViewChild} from '@angular/core';

@Component({
    selector: 'app',
    template: `
        <div id="myDiv">Some text</div>
    `,
})
export class AppComponent implements AfterViewInit {

    ngAfterViewInit() {
        console.log(document.getElementById("myDiv").innerHTML);
    }
}

So which one is more preferable way & why?
I have tried to find answer on google but not able to find any proper technical and detailed answer.

Thanks,

2

There are 2 answers

3
Elmehdi On

When using Angular, don't use document.getElementById("myDiv").innerHTML because you are not supposed to touch the DOM directly.
Instead you can use the following syntax @ViewChild('myDiv') myDiv: ElementRef and Angular is gonna get the DOM element for you.
This way you can be sure there won't be any unwanted behaviors related to manipulating the DOM directy.

I found a similar answer here.

0
Guerric P On

The reason why you should never use document.getElementById("myDiv") is that Angular's code is meant to be platform agnostic. There is a rendering engine for the browser, but there is also a rendering engine for the server. In case of server-side rendering, the browser's API (window, document, navigator, ...) don't exist at all. That's why Angular provides an abstraction layer that makes the code independent of the DOM.

So despite the fact that this kind of code could lead to unexpected behaviors (due to some DOM elements managed by Angular, and by native code at the same time), it makes your code "for the browser only" and you lose some of the Angular framework abilities.