Ronny Giezen
Ronny Giezen

Reputation: 645

Add value of material progress bar every second Angular10

I want to add value to the value of the progress bar on every second so I can do some actions when the progress bar is at 100. I have written the code below but it doesn't do anything.

Ts File:

export class ProgressSpinnerTest implements OnInit {

  color: ThemePalette = 'primary';
  mode: ProgressSpinnerMode = 'determinate';
  value = 0;
  sub: Subscription;

  ngOnInit(): void {
    this.sub = interval(1000).subscribe(x => {
    this.progressBar();
});
}

progressBar(): void {
  this.value + 10;
  if (this.value === 100) {
    console.log("done");
    this.value = 0;
  }
}
}

The Component:

<mat-card>
  <mat-card-content>
    <h2 class="example-h2">Result</h2>

    <mat-progress-bar
        class="example-margin"
        [color]="color"
        [mode]="mode"
        [value]="value">
    </mat-progress-bar>
  </mat-card-content>
</mat-card>

How can I make it so that it adds 10 to the value of the progress bar every second?

Upvotes: 1

Views: 776

Answers (1)

Dani
Dani

Reputation: 913

You can do this using the rxjs operators also:

  color: ThemePalette = 'primary';
  mode: ProgressSpinnerMode = 'determinate';
  progress: Observable<number>;
  ngOnInit(): void {
    this.progress = interval(1000).pipe(
      mapTo(10),
      scan((a, b) => a + b),
      takeWhile((value) => value < 100, true),
      map((value) => (value == 100 ? 0 : value))
    );
    this.progress.pipe(takeLast(1)).subscribe((_) => console.log('done'));
  }

And the html:

<mat-progress-bar 
  [color]="color"
  [mode]="mode"
  [value]="progress | async">
</mat-progress-bar>

It is a good practice to try avoid using subscriptions in your component, letting angular handle subscriptions using the async pipe.

Upvotes: 2

Related Questions