Progress Bar Modules

I am currently working on creating a customizable animated progress bar that can be utilized as follows:

<bar [type]="'health'" [percentage]="'80'"></bar>

It is functional up to the point where I need to adjust different percentages. It doesn't have to be completely dynamic, just when the page loads it should fill up the bar to the percentage specified above.

*bar.component.html*
<div class="bar-wrapper">
  <div class="bar-label">CSS</div>
  <div class="bar-container">
    <div class="bar-fill" [style.width.%]="percentage" [@barAnimation]="state"></div> <!-- I've tried various methods to set the CSS, but it remains as defined in the SCSS file. -->
    <div class="bar-percentage">{{percentage}}</div>
  </div>
</div>

bar.component.ts

@Component({
  selector: 'bar',
  templateUrl: './bar.component.html',
  styleUrls: ['./bar.component.scss'],
  animations: [
    trigger('barAnimation', [
      state('collapsed, void', style({ width: '0%'})),
      state('expanded', style({ width: '*'})), // <--- the width needs to be altered for each component.
      transition('* => expanded', [animate("4s cubic-bezier(0, -0.75, 0.25, 1)")])
  ])]
})
export class BarComponent implements OnInit {

  public state = "expanded";

  @Input() public type: String;
  @Input() public percentage: String;

  constructor() { }

  ngOnInit() {
    console.log(this.type + ", " + this.percentage);
  }

  public startAnimation() {
    this.state = "expanded";
  }
}

After spending quite some time experimenting with this, I realized using * might be the solution for adjusting the width property. Manually changing my scss file makes the bar function correctly. So, I guess the challenge lies in somehow setting the CSS width property.

Answer №1

Eliminate the barAnimation. Keep it simple and straightforward. :)

Just utilize a basic CSS transition on width. Here is some pseudo code to guide you:

CSS:

.bar {
    transition: width .5s ease;
    width: 0;
    height: 2px;
    background-color: green;
}

Template:

<div class="bar" [style.width.px]="width"></div>

Component:

@Component({...})
export class BarComponent {
    @Input() width: number = 0;
}

Whenever the width property is changed, the bar's width will expand with an animated effect based on the CSS transition.


To test it, set a timer and increase the width to 50:

@Component({...})
export class BarComponent implements OnInit {
    @Input() width: number = 0;

    ngOnInit() {
        setTimeout(() => this.width = 100, 1000);
    }
}

After one second, the width will increase to 100 pixels.

If you prefer using percentages instead of pixels, feel free to do so -- it should not impact the animation itself.

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

Encountering an issue when retrieving the value from a template-driven Angular form

Encountering an issue in the register function regarding storing the form control value. When using "let firstname", "let lastname", and "let email", I am receiving the error [tslint] Identifier 'firstName' is never reassigned; use 'const&a ...

Padding on a flex item nudges a neighboring flex item out of place

Encountering an issue - within a div container, I have 4 nested divs using the grid system. Oddly enough, the third div in the grid is not behaving as expected. When setting a margin-bottom for this div, instead of creating space at the bottom, it pushes ...

The Extended Date type is indicating that the function cannot be located

I came across this helpful gist with date extensions: https://gist.github.com/weslleih/b6e7628416a052963349494747aed659 However, when attempting to use the functions, I encountered a runtime error stating: TypeError: x.isToday is not a function I foun ...

Challenges in integrating a PrimeNG Angular2 component with DynamicDialogRef, as well as the difficulties encountered when attempting to do

I am currently working on implementing a component that utilizes dynamic dialog and requires a direct usage. In the DynamicDialog example, there is a constructor in the car demo list component. constructor(private carService: CarService, public ref: Dynami ...

Generate a fresh line within the source code

Currently, I am facing a challenge with dynamically loading CSS, JS, and other components as it appears messy when viewed from the source. Although this issue does not impact functionality, I am not satisfied with how it looks in the source code. When exam ...

Different "criteria" for CSS wildcard selectors using Selenium

There are several CSS webelements on my page with ids in the format: cell_[number]-button_[number] I am attempting to target ALL of these elements by using Selenium to locate all elements that begin with cell and include button: var elements = Util.driver ...

Is it considered an anti-pattern in TypeScript to utilize BehaviorSubject for class or object properties?

When working with Angular, I find myself frequently displaying members of classes in an Angular HTML template. These classes often share common members structured like this: class Foo { bar: string; bas: Date; } There are instances where I need to ...

Unable to apply "@angular/fire" using ng add command because the package does not have schematic support

Just completed the upgrade to Angular CLI 12.0.0, alongside Node 14.17.0 and npm 7.13.0 Encountering an issue when attempting to integrate Angular Fire into my project: ng add @angular/fire The following message pops up: The package @angular/[email ...

The Angular HttpErrorResponse is a class used for handling

I am encountering an issue while attempting to retrieve a user's cart by submitting the username in the request URL. list: PanieDto[] = []; @Input() listform: PanieDto = new PanieDto(); isLoggedIn = false; showAdminBoard = false; showModeratorBoard = ...

Using jQuery to generate nested lists

I have attempted various solutions for creating nested ul/li elements without success. I am a beginner in JavaScript and struggling with this task. The data is retrieved after the page has loaded, and it looks like this: data = { "key1": ["value1", va ...

Why does my ng2 validator insist on enclosing my validation messages in the newline character ` `?

Following the error-text-accumulation pattern outlined in the angular2 documentation, I gather all messages from my custom form validators and combine them into a single string to present to the user: onValueChanged(data?: any) { if (!this.heroForm) { r ...

The React type '{ hasInputs: boolean; bg: string; }' cannot be assigned to the type 'IntrinsicAttributes & boolean'

I recently started learning react and encountered an error while passing a boolean value as a prop to a component. The complete error message is: Type '{ hasInputs: boolean; bg: string; }' is not assignable to type 'IntrinsicAttributes & ...

Enhance ngx-bootstrap's tab content with ngx-scrollbar functionality

Currently in my project, I am utilizing bootstrap 4 and ngx-bootstrap. One requirement I have is to develop a component consisting of 2 scrollable divs that can be switched by tabs. I was hoping to demonstrate a sample application on stackblitz, but unfor ...

Considering the move from AngularJS 1.4 to Angular 8 is a significant one, the question arises: should one opt to migrate to 1.5 before upgrading

After conducting extensive research, I am still unsure of the best approach for migrating a large, poorly structured program to Angular 8 (or at least Angular 7). The options of vertical slicing, horizontal slicing, or a complete rewrite all seem dauntin ...

What is the necessity of ngrx/store when services and localStorages are available for use?

When it comes to Angular, we rely on ngrx/store to manage the state. However, I question whether all tasks can be effectively handled using services alone. What benefits does implementing the ngrx/store package offer? Your insights would be greatly appre ...

Guide on creating a Jasmine test for a printer utility

Currently, I am working on writing a Jasmine test for the print function shown below: printContent( contentName: string ) { this._console.Information( `${this.codeName}.printContent: ${contentName}`) let printContents = document.getElementById( c ...

Creating a parameterized default route in Angular 2

These are the routes I've set up: import {RouteDefinition} from '@angular/router-deprecated'; import {HomeComponent} from './home/home.component'; import {TodolistComponent} from './todolist/todolist.component'; import { ...

Error occurs in Windows script while running a project installed globally

Upon installing my project globally, I encountered a Windows Script Host error. https://i.stack.imgur.com/unFVu.png What steps can I take to resolve this issue? The following is my JavaScript code snippet: Object.defineProperty(exports, "__esModule ...

Angular2 app fails to update after emitting an event

I need help with a child component responsible for updating phone numbers on a webpage. The goal is for the application to automatically display the changed phone number once the user hits the 'save' button. Here's a visual of how the appli ...

Troubleshooting a Minimum Width Problem in HTML and CSS

Having trouble with setting a minimum width for a specific section. When the browser size is smaller than the set minimum width, the background color/image defined by CSS does not expand beyond the window size. Essentially, when scrolling horizontally to v ...