Shift 'n Tab
Shift 'n Tab

Reputation: 9443

How to determine percentage value in a mat-progressbar while executing functions and methods call?

Currently, i have an application which read multiple CSV files that contain a lot of data and do some calculation, conversion, parsing, appending, and formatting to the content then preview the cleaned data (final form) inside a list in a dialog.

Process

  // Call to read the files
  fileReader(files: FileList, i: number): void {
    const self = this;
    const file = files[i];
    const reader = new FileReader();

    reader.readAsBinaryString(file);
    reader.onload = function (e) {
      self.fileReloader(e, files, i);
    };
  }


  // Perform process of all file content while there is some to read
  // otherwise end the process.
  fileReloader(e: any, files: FileList, i: number): void {
    const bin = e.target.result;

    try {

      // Do parsing, converting the content of CSV file.
      ... Omitted lengthy codes


      // Load another file if there is any.
      if (i < files.length - 1) {
        // Load the next file
        this.fileReader(files, i + 1);

      } else {

        // If there is none to CSV files to read at this point which ends
        // the whole process and opens a dialog.

      }

    } catch (error) {
      throw something_good;
    }
  }

Usage

  onFileSelect(e: any): void {
    const target: DataTransfer = <DataTransfer>(e.target);
    this.fileReader(target.files, 0);
  }

As you can see, it is a recursive call where some lengthy process takes place. But how do I determine progress bar 100% value and increment when the process is progressing? I could simply achieve this by using an indeterminate mode in the progress bar but I want a determinate mode.

Upvotes: 1

Views: 4949

Answers (1)

Leon Radley
Leon Radley

Reputation: 7682

I would have a Subject<number>() which emits values from 0 - 100 Then I would have the progressbar subscribe to the values

<mat-progress [value]="progressSubject$ | async"></mat-progress>

By knowing how many files you are going to read, you can determine the percent value.

const filePercent = 100 / (files.length - 1); // how many percent each file represents.

then after each file is done processing call

progressSubject.next(filePercent * i);

Upvotes: 3

Related Questions