Implementing dynamic progress bar updates in an Angular application using Bootstrap

Seeking to create a progress bar in a Word object for a language vocabulary training app, displaying the number of correct and wrong answers.

<div class="progress">

      <div class="progress-bar progress-bar-striped progress-bar-animated bg-success" role="progressbar" [style.width]="word.correctAnswers" [attr.aria-valuenow]="word.correctAnswers" aria-valuemin="0" [attr.aria-valuemax]="totalAnswers"></div>
      <div class="progress-bar progress-bar-striped progress-bar-animated bg-danger" role="progressbar" style="width: 20%" attr.aria-valuenow="{{word.wrongAnswers}}" aria-valuemin="0" attr.aria-valuemax="{{totalAnswers}}"></div>
    </div>

the ts:

@Input()
  word!: Word;

  totalAnswers!: number;

  ngOnInit(): void {
    this.totalAnswers = this.word.correctAnswers + this.word.wrongAnswers;
  }

Encountering issues with displaying the progress bars despite attempted solutions. The green bar is not showing up and the red bar remains fixed at 20 percent. Adjusting its width leads to it disappearing entirely.

Answer №1

Utilize the following method to determine the percentage and assign it as the width using [style.width.%] notation.

Give this a try:

<div class="progress">
<div class="progress-bar progress-bar-striped progress-bar-animated bg-success" role="progressbar" [style.width.%]="(100 * word.correctAnswers)/totalAnswers" [attr.aria-valuenow]="word.correctAnswers" aria-valuemin="0" [attr.aria-valuemax]="totalAnswers"></div>
<div class="progress-bar progress-bar-striped progress-bar-animated bg-danger" role="progressbar" [style.width.%]="(100 * word.wrongAnswers)/totalAnswers" attr.aria-valuenow="{{word.wrongAnswers}}" aria-valuemin="0" attr.aria-valuemax="{{totalAnswers}}"></div>
</div>

Alternatively, with component variables:

  totalAnswers!: number;
  correctPercentage!: number;
  wrongPercentage!: number;

  ngOnInit(): void {
    this.totalAnswers = this.word.correctAnswers + this.word.wrongAnswers;
    this.correctPercentage = (100 * this.word.correctAnswers)/this.totalAnswers;
    this.wrongPercentage = (100 * this.word.wrongAnswers)/this.totalAnswers;

  }

<!-->

  <div class="progress">
<div class="progress-bar progress-bar-striped progress-bar-animated bg-success" role="progressbar" [style.width.%]="correctPercentage" [attr.aria-valuenow]="word.correctAnswers" aria-valuemin="0" [attr.aria-valuemax]="totalAnswers"></div>
<div class="progress-bar progress-bar-striped progress-bar-animated bg-danger" role="progressbar" [style.width.%]="wrongPercentage" attr.aria-valuenow="{{word.wrongAnswers}}" aria-valuemin="0" attr.aria-valuemax="{{totalAnswers}}"></div>
</div>

Answer №2

<div class="progress-bar progress-bar-striped progress-bar-animated bg-success" role="progressbar" [style.width]="word.correctAnswers" [attr.aria-valuenow]="word.correctAnswers" aria-valuemin="0" [attr.aria-valuemax]="totalAnswers"></div>

The green bar does not appear in the code above because the value assigned to word.correctAnswers, which is used to determine the width with style.width binding, lacks the percentage sign (e.g. 2% or 25%). It seems to only have a numerical value. To address this, you can modify the code as shown below to add the % sign.

<div class="progress-bar progress-bar-striped progress-bar-animated bg-success" role="progressbar"
      [style.width]="word.correctAnswers + '%'" [attr.aria-valuenow]="word.correctAnswers" aria-valuemin="0"
      [attr.aria-valuemax]="totalAnswers"></div>

Alternatively, you can utilize [style.width.%] for binding purposes.

<div class="progress-bar progress-bar-striped progress-bar-animated bg-success" role="progressbar"
      [style.width.%]="word.correctAnswers" [attr.aria-valuenow]="word.correctAnswers" aria-valuemin="0"
      [attr.aria-valuemax]="totalAnswers"></div>

After these adjustments, the green bar should now be displayed correctly based on the provided width.

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

Utilizing BehaviorSubject to dynamically display components based on conditions

I have a basic Service that looks like this: import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs'; @Injectable() export class HighlightsService { private _highlightedTab: string = ''; highli ...

The z-index overlapping problem in webkit browsers is a result of Angular 7 animations

I have implemented staggered animations in my Angular 7 application to bring elements to life upon page load. However, I am facing a strange z-index problem with one of my components. Here is the animation code: @Component({ selector: 'track-page& ...

Simple and quickest method for incorporating jQuery into Angular 2/4

Effective ways to combine jQuery and Angular? Simple steps for integrating jQuery in Angular2 TypeScript apps? Not sure if this approach is secure, but it can definitely be beneficial. Quite intriguing. ...

What is the best way to display values from a Localstorage array in a tabular format using a looping structure

I have set up a local storage key 'fsubs' to store form submissions as an array. Here is how I am doing it: var fsubs = JSON.parse(localStorage.getItem('fsubs') || "[]"); var fcodes = {"barcodeno" : this.form.value.barcode, "reelno" : ...

Adjust the tally of search results and modify the selection depending on the frequency of the user's searches within an array of objects

Seeking assistance with adding a new function that allows users to navigate to the next searched result. Big thanks to @ggorlen for aiding in the recursive search. https://i.stack.imgur.com/OsZOh.png I have a recursive search method that marks the first ...

Tips for integrating jsPDF with Angular 2

Encountering Error: jsPDF is not defined, while implementing the code below: import { Component, OnInit, Inject } from '@angular/core'; import 'jspdf'; declare let jsPDF; @Component({ .... providers: [ { provide: 'Window&a ...

What prevents TypeScript from automatically inferring tuple return types in RxJs streams?

When composing an observable stream, the map function infer is a union instead of a tuple. For instance: import { Component } from '@angular/core'; import { from } from 'rxjs'; import { map, tap } from 'rxjs/operators'; expo ...

Is there a way to convert my messages into different languages without relying on the 'translate' directive or pipe?

Currently, my Angular application is set up with ngx-translate for translation purposes. While it is currently monolingual, I am already looking ahead to the possibility of needing to translate it in the future. Everything is functioning perfectly, but I w ...

Encountering numerous issues during my attempt to perform an npm install command

After cloning a git repository, I encountered an issue when trying to run the app in the browser. Despite running "npm install," some dependencies were not fully installed. Upon attempting to run "npm install" again, the following errors were displayed: np ...

Ways to transfer arguments from a subclass component to its superclass

Currently in the process of upgrading from Angular 7 to Angular 12. I have multiple components that inherit from a shared base class, where constructor arguments are passed in. Main Component export abstract class PageBase implements OnDestroy{ const ...

Embedding content within various ng-template elements

I'm currently working on developing a button component (app-button) that can utilize multiple templates based on the parent component using it. <div class="ds-u-margin-left--1 ds-u-float--left"> <ng-container *ngTemplateOutlet="icon">< ...

How to import a node module into an Angular app through Angular CLI and load children in

My goal is to import a module from the node modules. This particular node module contains routes that I need to access. Here's what I want to achieve: I aim to configure my app.module to incorporate loadChildren from the module within my node module ...

When attempting to open an Angular modal window that contains a Radio Button group, an error may occur with the message "ExpressionChanged

I am brand new to Angular and have been trying to grasp the concept of lifecycle hooks, but it seems like I'm missing something. In my current project, there is a Radio Button Group nested inside a modal window. This modal is triggered by a button cl ...

Accessing an Array from a service method in Angular and passing it to my main component

Within my api-service.ts, I have an array that holds some data. public getData():Observable<any[]> { return Observable.toString[ObsResult]; } Now, in the main component, I am attempting to call the getData() method to render the data in ...

What steps should I take to resolve the issue of 'unable to locate the name 'OktaAuthService' error?

I am currently trying to incorporate authentication into an Angular application using Okta. I have carefully followed the step-by-step instructions provided in the documentation at this link: . However, I am encountering an error when attempting to start t ...

SystemJS is loading classes that are extending others

In my Angular2 application, I have two classes where one extends the other. The first class is defined in the file course.ts (loaded as js) export class Course { id:string; } The second class is in schoolCourse.ts (also loaded as js) import {Cours ...

Angular - Sharing data between components with response value

I am currently in the process of restructuring my project, focusing on establishing communication between unrelated components while also waiting for a return value from a function call. Imagine having component1 with function1() and component2 with funct ...

Angular6 Observables used in API service with dynamic arguments

In order to achieve the desired behavior, I am trying to implement a system where when a user selects a label from a dropdown menu, an API call is made with that specific label as an argument. Subsequently, a chart should be redrawn using the data received ...

The menu's mouseover event is activated when hovering over the inner element

Whenever a user hovers over a specific element, a menu appears. This menu remains visible only as long as the user is hovering over it. However, the issue arises when there are elements within the menu itself, causing the menu to hide when the user hovers ...

Unable to create a new collection in Firebase Firestore

I encountered an issue while trying to add a collection in Firebase Firestore using the function .collection(doc).set. Despite finding the new user in authentication in Firebase, the collection was not created and the console displayed an error message. ...