Reputation: 53
I'm trying to implement a progress bar that moves in accordance with a process that's running in my Angular program.
<div mat-dialog-content>
<mat-progress-bar mode="determinate" [value]="loadingVal"></mat-progress-bar>
</div>
var loadingVal = 0
var increase = 100 / array.length
for (i = 0, array.length, i++) {
....
this.loadingVal = this.loadingVal + increase
}
As you can see, I am increasing the loadingVal with every iteration of the loop. However, the progress bar is not moving, it is staying at 0 until the process is complete. Am I doing something wrong, or is there another way to move the progress bar along?
Upvotes: 0
Views: 2590
Reputation: 1592
This cannot work that way because JavaScript is single-threaded. Angular will run its change detection after the complete function returns. If you want to see some progress, try to use window.setTimeout(() => this.loadingVal += increase, 500 * i);
within your loop. The setTimeout()
function will queue those callbacks and Angular can perform the change detection in between.
Example
Controller:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
loadingVal: number = 0;
ngOnInit(): void {
for (let i = 0; i < 100; i++) {
window.setTimeout(() => (this.loadingVal += 1), i * 100);
}
}
}
Template:
<mat-progress-bar mode="determinate" [value]="loadingVal"></mat-progress-bar>
Working example: https://stackblitz.com/edit/angular-ivy-kciqoy
Upvotes: 1
Reputation: 165
I think that it should be
[value]="loadingVal"
instead of
[value]=loadingVal
Upvotes: 0