In Angular, I am calling a function from an *ngFor loop and the entire loop runs twice when it should only run once

As @okan pointed out, Angular’s change detection is running twice, causing your *ngFor loop to run twice. This is intentional behavior by the framework when running in development mode, and should not happen in production mode.

While changing the Change Detection Strategy can be a good solution to this problem, I suggest instead that you refactor your code to isolate your app’s data more from the UI.

In this case, I would maintain separate arrays for whichever (or maybe both) arrays that are currently negatively affecting your *ngFor loop. Calculate whatever you need to, using the data that is not exposed to the UI. When everything settles, set the data that is exposed to the UI. This way, the *ngFor loop will still run twice (which again, is intended), but it won’t cause your calculation to run twice.

In general, I try not to have the UI directly invoke non-trivial code, and try to keep separation between the UI and the data model.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top