'Performance between JSON.parse and DOM iterating. Angular 12

One of my requirement is loading data in Mat table. We planned for two ways one getting the DOM as string from the database to render in Angular and another is forming array of object as string from database and parsing it before rendering in to table using JSON.parse and used as normal array to render MatTable. Here the issue is it contains click event.

By using innerHTML: It is not possible to trigger event from the string DOM from database. so we need to manually iterate the div and add event listener to it after view rendered. I choose ngAfterViewChecked because pagination we are doing is from server side. so each time we get data we will append string in innerHTML and add eventlistener to it.

By using JSON.Parser: In this case I will get data as string in JSON format so I will iterate it before rendering it in HTML.

Which is better for performance. I'm not having sample code with me please help me on this.



Solution 1:[1]

I would have voted "neither" on this one.

Angular is highly opinionated, which means there are good ways to do things (whatever works) and right ways to do things (ways that leverage Angular the way it was meant to be used).

Your components should be as simple and dumb as possible, using services for most of your logic and input/output.

So, I recommend creating a service that serves as the API call, probably with a method like

getMyTableData() {
  // Whatever code to generate payload, if any
  return this.httpClient<MyExpectedDataType>('/api/myApiMethod', seeDocumentationForThisArgument);
}

where the server responds with JSON and Angular extracts it. This is the way to do it because... I don't know! I don't need to because there are many things to worry about that I don't have to because it's baked into the framework for me! But I trust that if there was a better way to do it, they would have used it.

Bonus benefits:

  • because it's in a service instead of a component, it is easier to test.

  • Thanks to dependency injection, when testing your component it is easy to switch this service for a mocked version of the service.

Then your mat-table's data attribute can accept the observable returned by myService.getMyTableData(). You won't have to parse a thing.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 JSmart523