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,
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.