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); });
}
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.
Advertisement
Answer
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); } } }