Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Material 2: Progress Bar animation choppy

I'm trying to build a page with Angular that has various progress bars that represent the progress made for an action that takes a set amount of time. What I'm trying to do is use the Angular Material progress bar to make a smooth animation from time 0 to the end time. My current solution is simply to update the percentage of the process every 50ms, and set the value of the progress bar to that value. I'm accomplishing this using the rxjs timer, as seen below:

const start = new Date().getTime();
const source = timer(0, 50);
const subscribe = source.subscribe(() => {
  const time = new Date().getTime();
  if (time - start > length) {
    subscribe.unsubscribe();
  }

  this.progressValue = 100 * (time - start) / length;
});

Here is the progress bar HTML itself:

 <mat-progress-bar mode="determinant" [value]="progressValue"></mat-progress-bar>

The result, however, is a very choppy progression of the progress bar. Is there a better way to do this? I know the length of the process every time, so I feel that a smooth transition for that amount of time should be relatively easy. Thanks!

like image 614
EvanW Avatar asked Jan 06 '19 05:01

EvanW


1 Answers

here is what I came up with:

html

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

component:

@ViewChild(MatProgressBar) progressBar: MatProgressBar;
uploadPercentage$: Observable<number>;
uploadProgress$: Subject<HttpProgressEvent> = new Subject<HttpProgressEvent>();

ngAfterViewInit(): void {
    // wait until animation ends and only then change value
    this.uploadPercentage$ = this.progressBar.animationEnd
      .pipe(
        startWith({
          value: 0
        }),
        switchMap((animationState: ProgressAnimationEnd) => this.uploadProgress$
          .pipe(
            map((progress: HttpProgressEvent): number => this.progressToPercents(progress)),
            distinctUntilChanged((val: number) => animationState.value !== val)
          )
        ),
      );
  }

like image 106
Nodarii Avatar answered Nov 15 '22 22:11

Nodarii