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,