how to implement a progress bar with a percentage indicator using Angular 9

Is there a way to create a progress bar in Angular 9 that updates as an image is selected for upload?

I have this code that tracks the upload progress of a file and displays it as a percentage.

 let elemnt = document.getElementById('progress');

 this.managersService.UpdateWithFile(editModel, this.personalInfo.id, '/Manager/PersonalInfo').subscribe(
      (upload: HttpEvent<any>) => {
        switch (upload.type) {
          case HttpEventType.UploadProgress:
            if (upload.total) {
              this.queueProgress = Math.round(upload.loaded / upload.total * 100);
              if (this.queueProgress <= 100 && this.queueProgress > 0) {
                elemnt.style.strokeDashoffset = 440 + 45 + 'px'
                this.cdRef.detectChanges();
              }
            }
            break;
          case HttpEventType.Response:
            if (upload.body['isSuccess']) {
              this.queueProgress = null;
              this.alertService.success('', upload.body['message']);
              this.router.navigate(['/managers']);
            } else {
              this.cdRef.detectChanges();
            }
            this.loading = false;
            this.queueProgress = null;
            break;
        }
      },
      error => {
        this.loading = false;
        this.queueProgress = null;
      });
  }

In this segment, I retrieve the percentage value and attempt to adjust the size using HTML pixels.

if (this.queueProgress <= 100 && this.queueProgress > 0) {
                elemnt.style.strokeDashoffset = 440 + 45 + 'px'
                this.cdRef.detectChanges();
              }

However, the issue lies in the fact that this line of code only executes once when the

elemnt.style.strokeDashoffset = 440 + 45 + 'px'
condition is met. I need it to update every time the queueProgress value changes. I've tried using this.cdRef.detectChanges();, but it doesn't seem to work. What could be the problem? How can I resolve this?

Answer №1

Ensure that when setting the offset on each HttpEvent, you are utilizing the variable this.queueProgress instead of 485px (440 + 45). Neglecting to do so is the reason why no changes are visible. To calculate the percentage, multiply it by the required maximum offset.

const maxOffset = 100;
elemnt.style.strokeDashoffset = 440 + (maxOffset * this.queueProgress / 100) + 'px'

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Verify the presence of an email in MongoDB in real-time as it is being

This particular project utilizes js, mongoose, and node.js. If an email that is already in use is attempted during registration to create an account, the page will reload, all fields will be cleared, and a pop-up message using AJAX will notify the user tha ...

Unable to attach an onClick event handler to <TableRowColumn> element using Material-UI in React

In the past, I had a feature that allowed me to change the color of the text from red to green by clicking on a table cell. After introducing Material-UI in my React app and replacing the <td> tags with <TableRowColumn> tags, I noticed that th ...

transforming JSON information into tables on a webpage

Can someone help me with the challenge of incorporating a massive JSON file into an HTML table? I am encountering an issue where I continuously receive the error message Uncaught TypeError: v.forEach is not a function. Any guidance would be greatly appreci ...

Django inline formset posing challenges with deletion of forms

I am using an inline formset named WorkExperienceFormset to generate forms by clicking a button. However, I am facing an issue where I am unable to delete the forms when I click the button. forms.py: WorkExperienceFormset = inlineformset_factory(Employee, ...

Angular Unit Test - Overcoming CORS Issue During XMLHttpRequest Access

I am currently facing a CORS problem within my Angular test spec file. I am unsure of how to resolve this issue, which occurs in the second line. beforeEach(() => { fixture = TestBed.createComponent(FhcComponent); //THIS IS WHERE THE ISSUE ARISES ...

Error: Angular2 RC5 | Router unable to find any matching routes

I am currently encountering an issue with my setup using Angular 2 - RC5 and router 3.0.0 RC1. Despite searching for a solution, I have not been able to find one that resolves the problem. Within my component structure, I have a "BasicContentComponent" whi ...

Store the ajax call response in a dynamic function

Currently, I am in the process of creating a series of user-friendly formulas, similar to those found in Excel, for a form builder website. One of the features I have developed is a Lookup function that allows users to specify the value they want and the v ...

Updating the default value for react-i18next (stored in localstorage)

When utilizing a backend and language detector, an issue arises: The localstorage contains the key I18nextLng with the value en-US. How can we set the default value to be I18nextLng with the value En? init and other settings are as per the default docume ...

Encountering the "Cannot Retrieve" error in express.js while navigating to the ID of an object

I'm in the process of developing a blog web app that allows users to create articles. Once a user clicks on 'new article', they will be taken to a page with a 'post article' button. This button triggers a post request linked to my ...

Can a webpage be sent to a particular Chromecast device without using the extension through programming?

My organization has strategically placed multiple Chromecasts across our facility, each dedicated to displaying a different webpage based on its location. Within my database, I maintain a record of the Chromecast names and their corresponding URLs. These d ...

How come TinyMCE is showing HTML code instead of formatted text?

I have been working on integrating TinyMCE with React on the frontend and django(DRF) on the backend. After saving data from TinyMCE, it retains the HTML tags when displayed back, like this: <p>test</p> <div>Test inside div</div> ...

Developing a common module for use across deferred loading paths

I have been working on developing an Angular 11 application and am currently in the process of creating a SharedModule. My goal is to prevent loading common modules repeatedly across my lazy loaded routes. To achieve this, I created a shared module and imp ...

What sets Legacy JavaScript apart from its modern counterpart, JavaScript?

Exploring the distinctions in coding practices between JavaScript and jQuery, I came across an interesting concept known as Legacy JavaScript that I was previously unaware of. You can read more about it at this link: Selecting Elements in Different Ways: ...

What steps can be taken to troubleshoot a jQuery / JavaScript conflict?

I am facing an issue with my web page, which includes two WebUsercontrols(.ascx): one for a slide show and the other for FullCalendar. When running each user control separately, they work fine. However, when both are included on the same page, a script con ...

Does JSON.Stringify() change the value of large numbers?

My WCF service operation returns an object with properties of type long and List<string>. When testing the operation in a WCF application, everything functions correctly and the values are accurate. However, when attempting to call the service using ...

How can the outer function be connected to the resolve method of $routeProvider?

Here is a functional code snippet: $routeProvider.when('/clients', { templateUrl:'/views/clients.html', controller:'clientsController', resolve: { rights: function ( ...

How to submit the next row using jQuery AJAX only when the previous submission is successful without using a loop - could a counter

Currently, I am dealing with loops and arrays. My goal is to submit only the table rows that are checked, wait for the success of an Ajax call before submitting the next row. Despite trying various methods, I have not been successful in achieving this yet. ...

Display PDF file retrieved from the server using javascript

I am currently working on a web application using JavaScript, jQuery, and Node.js. I need to receive a PDF file from the server and display it in a new browser window. While I believe I have successfully received the file on the client side (the window sh ...

The npm outdated command seems to ignore the caret notation specified in the package.json file

When looking at a package.json file that contains the following: "devDependencies": { "grunt": "^0.4.5", "grunt-concurrent": "^1.0.0", "grunt-contrib-jshint": "^0.10.0", "grunt-contrib-watch": "^0.6.1", "grunt-dev-update": "^1.1.0", ...

Dealing with arrays in Typescript and flattening them using the RX

Struggling with a problem involving RXJS transformation in an Ionic 2 application. My goal is to flatten a JSON file into objects, here is the simplified JSON structure: [{ "language": "it", "labels": { "name": "Hi", }, "t ...