Navigating through Angular iterator loops

In one of my components, I have the following method:

public *numGen(): Iterator<number> {
    for (let i = 0; i < 5; ++i)
      yield i;
  }

Additionally, my HTML contains this snippet:

<p *ngFor="let n of numGen()">{{n}}</p>

I anticipated that this would display the numbers 0 to 4 in separate paragraphs as follows:

<p>0</p>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>

However, while it does produce the expected output, it also triggers an error message:

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. 
Previous value: 'ngForOf: [object Generator]'. Current value: 'ngForOf: [object Generator]'.

Does anyone have a solution to prevent this error from occurring?

Answer №1

Optimizing change detection in Angular can be achieved by utilizing the OnPush strategy, ensuring that bindings are only checked when there is a change within the component triggered by @Input or template events. This approach not only enhances performance but also establishes a more coherent pattern for triggering change detection.

@Component({
  // ...
  changeDetection: ChangeDetectionStrategy.OnPush
})

Explore here

If you encounter an error, it may be due to returning a new reference of the Generator object on every change detection cycle.


Alternatively, consider updating the generator instance only when necessary by leveraging the ngDoCheck hook. Although this method is invoked frequently, combining it with the OnPush strategy offers a balanced solution.

export class AppComponent  {
  generator: Iterable<number> = this.numGen();

  multiplier = 1;

  ngDoCheck(): void {
    this.generator = this.numGen();
  }

  times(): void {
    this.multiplier *= 2;
  }

  private *numGen(): Iterable<number> {
    for (let i = 0; i < 5; ++i) {     
      yield i * this.multiplier;
    }
  }
}

Example using ngDoCheck

Out of curiosity, what specific use case motivates your utilization of iterators/generators?

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

Ways to cycle through a generator?

Imagine having a large list that you need to loop through. >>> x=[] >>> for i in x: print(x) However, due to the size of the list, using a generator is a more efficient solution: >>> g=(i for i in range(10)) >>> g.__n ...

Developing a MEAN application with simultaneous servers running Express, NodeJS, and Angular 2

Currently, I am trying to establish a connection between my backend (NodeJS, Express) and frontend (Angular 2), but I am facing a hurdle in the process. When I run both servers separately, the client-side and server-side functionalities work correctly. In ...

"Unlocking the Secrets: Mastering Step Index Manipulation in Angular Arch

Looking for tips on changing the step index in Angular Arch Wizard. I have two forms on the same page and need to navigate to a specific step. Any ideas? <aw-wizard > <aw-wizard-step > <form role="form" > < ...

Combine several .ts files into one bundle called package.js

Here is the structure of my code: Foo.ts: export module Foo { export function load() { } } Bar.ts: export module Bar { export function load() { } } webpack.config.js: const path = require('path'); module.exports = { entry: { ...

Forward the request from Node.js to a Spring Boot service and return a response

Currently, I have an angular UI running on localhost:4200, a node server running on localhost:4000, and a spring boot service running on localhost:8080. My goal is to establish a flow from angular to node, then redirect to the spring boot service which co ...

Next.js v13 and Firebase are encountering a CORS policy error which is blocking access to the site.webmanifest file

Background: I am currently developing a website using Next.js version 13 in combination with Firebase, and I have successfully deployed it on Vercel. Upon inspecting the console, I came across two CORS policy errors specifically related to my site.webmani ...

What is the best way to eliminate duplicate files from an Angular input file?

Currently, I am working on a web application that includes a feature to upload files. For each file, there is a separate input field. The issue arises when a user selects a file from the same input field twice, resulting in two different files of the same ...

What is the best way to access data from a local JSON file in Gatsby when using TypeScript and GraphQL?

I'm updating my former gatsby site using TypeScript. I encountered an issue while trying to retrieve data from a local JSON file: There appears to be an error in your GraphQL query: Cannot find field "allNavigationLinksJson" on type "Q ...

Angular HttpClient Catch Return Value

In my quest to develop a universal service for retrieving settings from the server, I've encountered an issue. When errors arise, I want to intercept them and provide a default value (I have a predetermined configuration that should be utilized when e ...

What is the best way to execute a function once a timeout is finished? This timeout should be initiated by a click event in Typescript

I need to ensure that 'this.breakCheck();' is called only once after the timeout is complete, not with every iteration. Right now I have it set up to call on each iteration, which works but is not ideal. public startBreak(){ for(let i = this.b ...

Frontend receiving data from an unexpected localhost address even with proxy settings in place

My React frontend application has a proxy configured in the package.json file to connect to my Flask backend running on http://localhost:2371. However, when trying to fetch data from the backend using fetch("/members"), the frontend is unexpectedly fetchin ...

What might be causing the frequent failures in my Angular project pipeline?

I've been working on an Angular project and trying to successfully tag and push it to the development server using Git and GitLab. Unfortunately, after multiple attempts, I'm feeling quite lost as to what might be going wrong. This is an excerp ...

Ionic Firebase Scroll Dilemma

I have been attempting to automatically scroll to the bottom of a view when it loads, but I have tried several methods without success. Sometimes it stops in the middle of the screen, and I suspect this is because not all messages (30) are loaded yet. Her ...

How to successfully utilize TypeScript ES6 modules and RequireJS for registering Angular elements

I am in the process of updating a current Angular application that uses AMD with TypeScript 1.5 ES6 module syntax. Our modules are currently stored in separate files, and the main "app" module is defined like this... define('app', ['angular ...

The where clause in the Typeorm query builder instance is not functioning properly after its common usage

When fetching data for my relations, I opted to use QueryBuilder. In order to validate certain get request parameters before the index, I established a common QueryBuilder instance as shown below. // Common Get Query const result = await this.reserva ...

The name 'Diagnostics' cannot be located

I've downloaded the Typescript repository and am currently reviewing the code. However, I keep encountering this recurring error message: Cannot find name 'Diagnostics' This error pops up on lines that are similar to this: Diagnostics._ ...

Why does my ngFor consistently refresh while the array remains unchanged?

Issue at hand: Whenever I launch this component, the ngFor div continuously updates and causes my RAM to deplete. Typically, ngFor is triggered when the array is updated; however, in my case, the array (announcements) only updates once in the constructor. ...

Looking to observe a decorated method using Jest even if the decorator poses a hurdle to method execution?

In my TypeScript project, decorators are a crucial part of enhancing method behavior. However, I recently ran into a situation where a decorator could potentially block the execution of a method. To test this scenario using Jest, I aim to confirm whether t ...

Error: Certain Prisma model mappings are not being generated

In my schema.prisma file, I have noticed that some models are not generating their @@map for use in the client. model ContentFilter { id Int @id @default(autoincrement()) blurriness Float? @default(0.3) adult ...

Tips for resolving the issue: Encountered an unexpected token < when parsing JSON data at position 0 using the JSON.parse function

I encountered an error when working on the code mentioned in this post. After removing .json() from response.json() in my code snippet below, the error message changed: return this.http.post('http://localhost:3000/sign-up', body, {headers: head ...