Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Angular – interpolating values after every forEach iteration

I’m building an Angular app, and I’m trying to interpolate value of a string in every forEach iteration on an array of strings.
(quotesData is array of strings from which I’m taking values from)

My function looks like this:

export() {
this.quotesData.forEach(element => {
  this.quote = element;
  this.wait(1000); \\ <- manually written function to postpone next line execution for 1s
  console.log(this.quote);
});

}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The problem is that the value in HTML interpolation for {{quote}} doesn’t get updated until the last iteration ends. However, value for this.quote is properly updated and displayed in console and in Debugger after every iteration.

>Solution :

I’m not sure how your wait function is implemented but I guess it still running asynchronously. To troubleshoot it I would suggest increasing the time to 5000 for example and checking if the values are displayed immediately in the console or not.

Otherwise, here is a working example using async await:

import { Component } from '@angular/core';

@Component({
  selector: 'hello',
  template: `<button (click)="display()" >Display</button><h1>Hello {{quote}}!</h1>`,
})
export class HelloComponent {
  quotesData: Array<string> = ['A', 'B', 'C'];
  quote: string = '';

  wait(ms) {
    return new Promise((res) => setTimeout(res, ms));
  }

  async display() {
    for (let quote of this.quotesData) {
      this.quote = quote;
      await this.wait(1000);
      console.log(this.quote);
    }
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading