Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get an element by ID in Angular 7 component (TypeScript) and use its attributes in component

We can use the standard Javascript method to get the element by its id:

document.getElementById("dataBlock").innerHTML = "";

In Angular however, the preferred way to refer to an element is with a template reference variable:

<div #dataBlock></div>
<button (click)="dataBlock.innerHTML = ''">Clear content</button>

That variable also allows to access the element in code with the help of @ViewChild:

@ViewChild("dataBlock") block: ElementRef;

clearContent() {
  this.block.nativeElement.innerHTML = "";
}

My question is that, what would be the impact of above code on performance and memory in an angular application.

like image 680
TAB Avatar asked Jan 21 '19 14:01

TAB


1 Answers

While the outcome of those 2 lines of code are essentially doing the same thing. The reason for doing it the 'Angular way' is that Angular applications are not always meant to be ran in a browser. For example you can run Angular in a web worker which doesn't have direct access to the DOM.

Another reason is that it is a bit cleaner to have a component reference to a specific element instead of doing getElementById every time you need to access the element.

My question is that, what would be the impact of above code on performance and memory in an angular application.

Angular gets compiled to javascript so in an Angular SPA this doesn't have any big performance impact. If you want to measure exact performance / memory usage, I would recommend using an extension like lighthouse. Memory & performance optimisation in Angular is not so much about using the Angular framework, but how you divide your modules, how you lazyload and most important in a SPA - the initial load time. I recommend sticking to the Angular framework and let Angular take care of compile optimisation. You won't safe any measurable time by using getElementById over ViewChild.

Made a stackblitz measuring the time it takes to perform this.block.nativeElement.innerHTML = ""; - it comes out as 0 milliseconds.

like image 76
Jonas Praem Avatar answered Oct 05 '22 22:10

Jonas Praem