How does inspecting an attribute compare to examining the output of a function?

I am working on a component that contains a list of items:

list: Array<MyType>;

Users have the ability to select and deselect elements by clicking on them:

toggleItem(item: MyType) {
  if (this.selection.has(item)) {
    this.selection.delete(item);
    return;
  }

  this.selection.add(item);
}

The selected items are kept track of using a Set:

selected: Set<MyType> = new Set();

Now, I want to toggle a CSS class and change the title attribute based on whether an element is selected or not:

<button class="toggle"
        type="button"
        [ngClass]="{'selected': selection.has(item)}"
        [title]="selection.has(item) ? 'Select' : 'Deselect'"
        (click)="toggleItem(item)">
  {{ item.title }}
</button>

I recently came across advice suggesting it's not optimal to evaluate function calls in Angular templates as they may be invoked frequently for change detection. For example:

[ngClass]="{'selected': selection.has(item)}"

Instead, it might be better to check a variable or property of the object directly, like this:

[ngClass]="{'selected': item.selected}"

Is this true? And will my current implementation affect performance? Should I consider adding a property to each item indicating its presence in the Set?

Answer №1

When Angular runs change detection, it examines any variables in the template to see if they have been altered.

Checking model variables is simple for Angular, as it can just read their values to determine changes.

However, this process becomes more complicated when dealing with functions. Angular can only ascertain if a variable has changed by executing the function associated with it.

If the function simply returns a value in one line, there is minimal impact on performance. But if the function contains complex logic, it can significantly affect performance. This is because Angular will call the function every time it performs change detection to detect any alterations.

Therefore, it is not advised to include functions in data-binding syntax within templates.

NOTE: I also wrote a Medium Article on this topic. I recommend checking it out as it delves into improving performance of Angular Reactive Forms. It will give you a better insight into the points mentioned above.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having difficulties in Vue while attempting to access a particular row

I encountered an error message stating Uncaught TypeError: snapShotChnaged.forEach is not a function. My goal is to retrieve specific row data, which is why I am utilizing the doc method. retrieveSpecificDonation() { firestore .collection('d ...

Tips for targeting a specific div element within a webview using code in Android app development

During my exploration of focusing on a webview in Android development, I encountered a question regarding setting focus on a div element. Despite making the div element editable, neither webView.requestFocus() nor document.getElementById('container&ap ...

The footer seems to be losing its stickiness and not staying at the bottom when I

My goal is to create a sticky footer for my webpage. Once you click the add new sports button, a drawer slides out and the footer remains fixed at the bottom. However, as I scroll down the page, the footer moves up instead of staying in place. I have tried ...

Transferring information from an external JavaScript file to a Vue component

I am currently facing an issue with passing data from an external file called data.js to the component for its usage. The error I'm encountering states that the data is not defined. Below is the content of my data.js file: const data = [ { cha ...

Implementing Node.js on several domains with the help of express.vhosts()

I'm facing a challenge with my nodejs setup. I am in the process of developing a node server that will support multiple instances of app.js running simultaneously on the same system using express.vhost(). However, I seem to have hit a roadblock. The ...

Clicking on an icon to initiate rotation (Material UI)

Is there a way to toggle the rotation of an icon (IconButton) based on the visibility of a Collapse component? I want it to point down when the Collapse is hidden and up when it's shown. const [expanded, setExpanded] = useState<boolean>(false); ...

Java - Absence of stack traces detected

My software application is using up 100% of the CPU, which is half of the total capacity (200%). When I attempt to generate a thread dump with Thread.getAllStackTraces() or kill -3, I notice that certain threads are consuming a significant amount of CPU ti ...

Change the objectID or _id obtained from a MongoDB Stitch query into a string format and then perform mapping on

I'm running into an issue with querying a MongoDB Stitch database where I am getting different results. When I console log all my data, it shows up like this (notice the 'id: Uint8Array(12) [ 94, 67, 83, … ]​​​' item.find().asArra ...

What is the best way to eliminate HTML encoding from a string in Angular 4?

Looking for a simple solution to my problem. I have two strings that look like this: htmlStr = "&lt;strong&gt;News Body&lt;/strong&gt;"; htmlStr1 = "<strong>News Body2</strong>"; To display these strings on a website, I am usi ...

Arranging different API's in a table in ascending order of price

This task might be a bit confusing, but it should have a straightforward solution. I am working with two API links in JSON format to pull data into a table. Currently, all data from API1 is inserted into the table first, followed by data from API2. Both ...

No indication of component statuses in the augury feature

Augury is a useful Chrome extension for debugging Angular applications. However, I have encountered an issue where it is not displaying any states currently. My setup includes Angular version 5.1.0 and Augury version 1.16.0. ...

What could be the reason behind the absence of certain headers in the response from Angular.js?

Firstly, I will provide you with images of POSTMAN tests (you can find the link to the google drive containing postman.png at the end of this question) The issue at hand is that there is a client on angular.js and a Laravel API (without access to configur ...

Apologies, the process failed due to the following error: "bunsh: No such file or directory running bun dev

Today I switched to using Windows and decided to install Bun. However, when I tried running the script "bun dev", I encountered the following error message: Error: Failed due to error: bunsh: No such file or directory. Interestingly, when I run the same ...

QuickCopy - Capture only what's in view

Hi there, I have a question: I'm trying to figure out how to make a button copy only the visible text within the element with id="description". Can someone help me troubleshoot? HTML: <p id="description"> Test <span style="display:none"> ...

AngularJS: Error encountered when trying to assign a value to a read-only property in the ng-submit directive

I've been working on a personal project to practice angularJS, but I've encountered a problem that seems unsolvable to me. The issue arises when I try to utilize the submitLogin() function in my LoginCtrl.js file upon form submission. An error m ...

What is the best method for creating a fade effect on a div background?

I am trying to animate a div with the id #test from a 0 opacity background to an opacity of 0.7 using CSS rgba values, but for some reason, the .animate function is not working as expected. Here is my CSS: #test { background-color: rgba(0, 0, 0, 0); ...

Displaying MySQL data on an HTML page with Node.js

Hello there, I recently started delving into Node.js for the first time. My current project involves fetching data from MySQL and displaying it on my HTML page. However, when I try to access my website at http://localhost:3000/index.html, I encounter an er ...

Blend the mouseover effect with the addition of specific class IDs on several elements

I'm reaching out for assistance because I’m struggling to fix this JavaScript code the way I want to. Essentially, what I am trying to do is add the class "typewriter" to the element with the id of "textanimation" when it is being hovered over, and ...

What is the proper way to bind CoreUI's CSwitch component?

I am trying to incorporate the CSwitch component into a DevExtreme data grid. While the DxSwitch component functions correctly, I am unable to get the CSwitch to work properly. It seems like I might be using the wrong binding. Could that be the issue? < ...

Quickest algorithm for hashing large quantities of UINT64 RGBZ image pixel data

After conducting tests on millions of 48-bit RGB pixels using three different hashing algorithms, I found that the performance differences were negligible. Among them, xxHash by Yann Collet had the fewest collisions and the lowest product of time and colli ...