In Angular, you can make a download progress bar with a percentage by
1.In your Angular project, first install the @angular/material and @angular/cdk packages:
npm install @angular/material @angular/cdk
2.Import the MatProgressBarModule and MatProgressSpinnerModule modules from the
@angular/material
package in your Angular module:
import { MatProgressBarModule, MatProgressSpinnerModule } from '@angular/material'; @NgModule({ imports: [ MatProgressBarModule, MatProgressSpinnerModule ], // ... }) export class AppModule { }
3.Next, import the @angular/common/http package’s HttpClient module and HttpEventType enum:
import { HttpClient, HttpEventType } from '@angular/common/http';
4.Utilizing the constructor, add the HttpClient service to your component or service:
constructor(private http: HttpClient) {}
5.Make a function that requests a download and tracks its progress:
public percentDone: number = 0; public downloadFile() { this.http.get('https://example.com/file.zip', { responseType: 'blob' }) .subscribe(event => { if (event.type === HttpEventType.DownloadProgress) { // Update the progress bar with the download percentage const this.percentDone = Math.round(100 * event.loaded / event.total); console.log(`Downloaded ${this.percentDone}%`); } else if (event.type === HttpEventType.Response) { // Save the downloaded file const file = new Blob([event.body], { type: 'application/zip' }); const fileURL = URL.createObjectURL(file); window.open(fileURL); } }); }
6.Use the mat-progress-bar and mat-progress-spinner components in your component’s template to display the progress bar and percentage:
<mat-progress-bar mode="determinate" [value]="percentDone"></mat-progress-bar> <mat-progress-spinner mode="determinate" [value]="percentDone"></mat-progress-spinner> <p>{{percentDone}}%</p>
The mat-progress-bar and mat-progress-spinner components’ value attributes can be bound to using the percentDone property, and the percentage can also be shown as text.
This shows how to use Angular to make a material design download progress bar with a percentage. Using the many options and styles offered for the mat-progress-bar and mat-progress-spinner components, you may alter the progress bar’s design and behavior as well as the behavior of the percentage.