What could be causing the ng-if function to continuously loop?

I have encountered an issue where I am passing a boolean function in the ngIf attribute instead of a boolean condition in my HTML template file. This boolean function seems to be repeating itself depending on the amount of data present in the variable 'messages'. For example, if there are 2 objects in 'messages', the value of 'ctr' in the console is increasing from 1 to approximately 69, rather than just 1 or 2. What could be causing this behavior and how can it be avoided when passing a function in the ngIf attribute?

HTML

<ion-row *ngFor="let message of messages; let i = index; trackBy:trackByMsgId">
      <ion-badge *ngIf="isNewDate(i)" color="primary" class="ion-margin">{{message.time | date: 'longDate'}}</ion-badge>
</ion-row>

TS

let ctr = 0;
isNewDate(i) {
    this.ctr += 1;
    console.log('ctr: ', this.ctr);
    return true;
}

Answer №1

Every time Angular performs ChangeDetection, the isNewDate() function is called due to unpredictability in its return value. This means the function needs to be executed each time change detection runs, as explained in the ChangeDetectionStrategy.

The updating of the DOM is a crucial part of the ChangeDetection process, with the ngFor directive playing a role in this update and triggering Angular's ChangeDetection. Therefore, if you have an array with a length of 4 and ChangeDetection runs 4 times for each item, your function will be called 16 times. However, the component variable ctr will be reset for each item. For a demonstration, refer to the example on Stackblitz. Many thanks to @Adam for the helpful comment, and based on the insights from the article mentioned in the link below:

While using function calls in Angular templates may be technically valid and convenient, they can lead to significant performance issues.

Therefore, it is not recommended to use function calls in Angular template expressions as it goes against best practices.

To avoid using function calls, consider following these solutions:

  1. Utilize pipes
  2. Manually compute values and update specific Variables in app.component.ts to be utilized in the template (app.component.html).

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

Exploring NuxtJS Vuex Module namespaces and mutation enumerations

My NuxtJS website has a Vuex store with a root state and a module located at store/shop/cart/state.ts. Within the module, there is a file called store/shop/cart/mutations.ts. import { MutationTree } from 'vuex'; import { CartState } from './ ...

Determine the date and time based on the number of days passed

Hey there! I have a dataset structured like this: let events = { "KOTH Airship": ["EVERY 19:00"], "KOTH Castle": ["EVERY 20:00"], Totem: ["EVERY 17:00", "EVERY 23:00"], Jum ...

Transferring images between Node.js and Angular

I've been working on sending images from the server to the client, and after doing some research, I found that transferring the data as an ArrayBuffer and then converting it to a Blob on the frontend is the most efficient solution. However, I've ...

Troubleshooting the Hide/Show feature in React Native

As a newcomer to React Native development, I am attempting something simple. Within a React Class extending Component, I have 4 components <TouchableOpacity>. In the render function, my goal is to hide three of these components while pressing on one ...

A helpful guide on retrieving user login details before launching an application by accessing JWT tokens stored in Cookies

In my angular project, I am implementing SSO login to generate a JWT token. Prior to initializing the application, I aim to retrieve the logged-in user's details and store them at runtime. Furthermore, I intend to utilize this user data in Route guard ...

The 'substr' property is not found in the type 'string | string[]'

Recently, I had a JavaScript code that was working fine. Now, I'm in the process of converting it to TypeScript. var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; if (ip.substr(0, 7) == "::ffff ...

Retrieving data from a database and displaying rows in a FormArray with Angular 5

As a newcomer to angular, I've created an event component where users can enter the event name along with details of packages. The functionality allows for creating multiple packages with the ability to add and remove rows using FormArray. While ever ...

I have implemented the ngx-bootstrap datepicker feature to automatically format any numbers typed into the input field

I am currently using a Bootstrap date picker plugin where, if I type a number, it automatically formats it (force parses it). However, I am looking for a way to disable this "force-parse" feature in the Bootstrap date picker. For example, if I enter four ...

Calculate the minimum, maximum, and average values within an array containing nested elements

I want to calculate the min, max, and average values for nested data that already have these values precalculated. Essentially, I'm looking for the average of averages, min of min, and max of max. I have a large dataset that includes the min, max, an ...

When attempting to update a document using the PUT method in the MEAN stack, no changes are being applied

My application is designed to perform CRUD operations, it's very simple. I'm trying to update the information of a book but it's not working. What should I change? Additionally, I'm encountering this error: core.js:6210 ERROR TypeError ...

Using jest-dom without Jest is definitely an interesting challenge that many developers may

Can anyone help me with extending Typescript interfaces? I have come across a situation that I am trying to solve. In my tests, I am utilizing expect without using Jest directly (I installed it separately and it functions properly). Now, I am interested ...

How to format decimals in Typescript/Angular with a pipe: comma or dot?

I've recently developed a custom pipe and I'm looking to enhance it by adding commas or periods to thousands values. For instance, 1000 should be displayed as either 1,000 or 1.000. Here is the code snippet for my custom pipe: import { Pipe, Pi ...

An error has occurred in Typescript stating that there is no overload that matches the call for AnyStyledComponent since the update to nextjs

Upgraded to the latest version of nextjs, 13.3.1, and encountered an error in the IDE related to a styled component: Received error TS2769 after the upgrade: No overload matches this call. Overload 1 of 2, '(component: AnyStyledComponent): ThemedSty ...

Unable to implement the `omega/theme.css` file within the angular.json configuration

"styles": [ "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css", "node_modules/bootstrap/dist/css/bootstrap.min.css", "src/styles.css", "node_modules/primeicons/primeicons.css", ...

The push action in NavController is not displaying Google Maps as expected

Trying to display a map upon clicking a button is proving challenging for me. It appears that the function NavController.push() does not work as expected, while NavController.setRoot() does. Despite not encountering any errors, I am unable to identify the ...

Troubles with Node and TypeScript: inability to detect jQuery

I'm currently facing some challenges with node and typescript that are causing issues in my Visual Studio 2015 projects. In the solution, I have two projects named Web and WebAPI. Both projects have node.js installed, each with their own node_modules ...

What is the method for importing the merge function from "lodash/merge" in TypeScript?

When using ES6, it's possible to import only a single function from a library in order to reduce the overall bundle size. For example: import merge from "lodash/merge" But in TypeScript, the statement above can trigger a compile error: Cannot find m ...

How to securely retrieve a document by integrating Angular 2 with a web API

I am currently working on an Angular 4 and web API application where I am attempting to download a file using Web API and TypeScript Blob. The code below showcases how this process is executed. However, upon trying to open the downloaded image, I encounter ...

Having trouble executing ng build --prod in Azure CICD pipelines

Having trouble setting up my application's CI/CD in Azure as the build process keeps failing. I've gone through my YAML configuration and tried multiple solutions found online, but it still doesn't work. This is the YAML setup I have: ...

Issue with Next.js: Callback function not being executed upon form submission

Within my Next.js module, I have a form that is coded in the following manner: <form onSubmit = {() => { async() => await requestCertificate(id) .then(async resp => await resp.json()) .then(data => console.log(data)) .catch(err => console ...