Using asynchronous data in Angular 2 animations

Currently, I have developed a component that fetches a dataset of skills from my database. Each skill in the dataset contains a title and a percentage value.

My objective is to set the initial width value of each div to 0% and then dynamically adjust it to the correct percentage once the HTTP request returns with the data. This adjustment should be animated, showing the divs expanding from left to right as the percentage increases (visualized by a color change within the div).

I am seeking advice on the best approach to achieve this animation effect within an Angular 2 environment. While I am aware of the animation property available in the component decorator, I am unsure how to integrate it seamlessly with the asynchronous results received.

The key aspect of my query lies in effectively handling the asynchronously fetched data to implement a smooth animation representing the percentage increase. My current implementation immediately displays the final result without triggering any animation – which is essential for my project requirements.

I understand that there are multiple strategies to accomplish this task, but I would appreciate guidance on selecting the most efficient solution.

Below is the code snippet for reference:

import { Component, OnInit } from '@angular/core'
import { SkillsService } from './skills.service'

@Component({
  selector: 'skills',
  template: `
    <section class="skills">
      <div *ngFor="let skill of skillsService.skills$ | async">
        <div class="skills__bar" [style.width]="skill.percentage + '%'">
          <h3 class="skills__title">{{skill.title}}</h3>
        </div>
      </div>
    </section>
  `,
})
export class SkillsComponent implements OnInit {

  constructor(private skillsService: SkillsService) {}

  ngOnInit() {
    this.skillsService.fetchSkills()
  }
}

Your input and suggestions on this matter are highly appreciated. Thanks in advance!

Answer №1

To achieve a smooth transition in CSS, follow this example:

//Example for demonstration purposes only.
$("#get-skills-btn").on("click", function() {
  var randomValue = Math.random();
  $(".skills__percentage").css("transform", "scaleX(" + randomValue + ")");
});
.skills__bar {
  background-color: silver;
  text-align: center;
  position: relative;
}
.skills__percentage {
  background-color: green;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  transform: scaleX(0);
  transform-origin: left;
  transition: transform 300ms cubic-bezier(0.175, 0.885, 0.32, 1.275);
}
.skills__title {
  position: relative;
  z-index: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="skills">
  <div>
    <div class="skills__bar">
      <div class="skills__percentage"></div>
      <h3 class="skills__title">{{skill.title}}</h3>
    </div>
  </div>
</section>


<button id="get-skills-btn">
  Fetch Data
</button>

If you are working with Angular, consider using the following code snippet:

[style.transform]="scaleX(skill.percentage/100)"

Answer №2

To achieve this functionality in Angular 4.2 and higher, we can utilize the @angular/animations library.

<div [@listParent]="len" class="list">
  <div *ngFor="let item of itemsAsync | async" [style.width]="item.val" class="item">
    {{item.name}}
  </div>
</div>

The animation listParent is defined in the component decorator as follows:

animations: [
  trigger('listParent', [
    transition('* => *', [
      query(':enter', style({ width: 0 })),
      query(':enter', animate('1.6s', style({ width: '*'})))
    ])
  ])

The listParent animation will be activated whenever the component property len undergoes a change.

Feel free to test out the animation on this plunker by clicking either the Get one or Get multiple button.

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

The magic of $.ajax lies in its ability to load an unexpected URL, diverging from my original

Every time I send a request using an absolute URL, Ajax is posting the wrong URL. For instance, when I request "http://localhost/app/home/session", it mistakenly calls "http://localhost/app/home/home/session" var baseURL = function(link) { var url = & ...

What could be the reason for my router navigate function not functioning properly in Angular 8?

I need help with redirecting to another component in my Angular application. Currently, I have the following code: HomeComponent checkUrl(reference) { if (reference != this.ref) { this.router.navigate(['/еrror']); } } Thi ...

Positioning HTML elements using CSS and avoiding the use of tables

I'm struggling with my clear CSS declarations. This is how I'd like it to appear: View the Fiddle demo HTML: <div id="timesheeteditor"> <div id="weekselector"> <div>Week 1</div> <div>Week 2</div> ...

What is the best way to reset form after submission in Next.js?

I have a contact form and I want all the form values to be cleared after submitting the form. I've tried the following code, but the values of the form remain unchanged after submission. What could be causing this issue and how can it be resolved? ...

Is it feasible to evaluate a Typescript method parameter decorator at request time in a nodejs+nestjs environment rather than just at build time?

Looking to simplify my handling of mongodb calls with and without transactions in a single service method by writing a decorator. This would help eliminate the repetition of code and make things more efficient. Key points for usage: • Service class has ...

Expanding text area size dynamically in Nuxt3 using Tailwind CSS

Is there a way to expand the chat input field as more lines are entered? I want the textarea height to automatically increase up to a maximum of 500px, and adjust the height of .chat-footer accordingly. Below is a snippet of my code. <div v-if="ac ...

Troubleshooting Typescript & Express Routing Issue

I am currently following a tutorial on how to set up a simple express-typescript application. However, I am encountering some difficulties with my routes not working as expected. Despite searching for similar problems and solutions, I haven't found an ...

Struggling to integrate buttons into an h2 element with the use of createElement() and appendChild() in HTML/CSS/JS

As I work on developing a website, one of the features I've been implementing is the ability for users to add books to a list and then review or delete them. The process was smooth sailing until I reached the point of adding buttons for these actions. ...

How to mute a particular warning in development mode with Next.js

Currently in the process of transitioning a CRA app to Next.js in order to enhance SEO. During development, I encountered the following warning: Warning: 'NaN' is an invalid value for the 'left' css style property. I am aware of the s ...

Why does LESS keep prompting me with missing elements?

I am currently working on my first project using Less and have been following a tutorial closely. However, when I try to compile with lessc, I encounter the following error: ParseError: Unrecognised input. Possibly missing something in C:\Path\t ...

Error injecting Angular components

Here is the structure of my HTML file: <html> <head> <title>PLD Interaction pattern</title> <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css"/> </head> <body ng-app="myT ...

Error Alert: Accessing the 'email' property on the 'UserCredential' type in Angular and Firebase is not allowed

import { Injectable } from '@angular/core'; import { Router } from '@angular/router'; import { User } from './../classes/user'; import { AlertService } from './alert.service'; import { Alert } from './../classes ...

What is the process for changing CORS origins while the NodeJS server is active?

Currently, I am in the process of modifying the CORS origins while the NodeJS server is operational. My main goal is to replace the existing CORS configuration when a specific user action triggers an update. In my attempt to achieve this, I experimented w ...

Can the Angular link function activate the change event?

I am facing an issue with my Angular directive that includes a link function. Inside this function, I am initializing a jQuery plugin which can be seen in action here: https://plnkr.co/edit/58nOhypt6FRdI4At5jwu. The problem arises when every time the dire ...

What is the process for performing the "extract function" refactoring in JavaScript?

Are there any tools for extracting functions in JavaScript similar to the "extract function" refactoring feature available for Java and jQuery developers in Eclipse or Aptana? Or perhaps in another JavaScript/jQuery IDE? ...

If the next element in the sequence happens to be the final element, then conceal a separate

Continue pressing the downward button consistently on until you reach the bottom. The down arrow should disappear slightly before reaching the end. Is there a way to achieve this using the code provided below? I'm new at this, but I believe I need t ...

Efficient Techniques for Deleting Rows in a Dynamic JavaScript Table

I'm facing an issue where I want to remove each line added by the user, one by one. However, my current program is removing all the rows from the table instead of just one at a time. The objective is to allow the user to remove a specific row if they ...

Ways to rearrange an object with javascript

I am looking to restructure my object by removing a nesting. How can I achieve this using JavaScript? Actual: var a = [ { clickedEvents: { 'event-element': 'a', 'event-description': & ...

An error has occurred: Noty (notification library) is not defined in this AngularJS Web Application

I am currently diving into the world of AngularJS and building a web application from scratch. As a newbie to AngularJS, I want to point out that I might be missing something crucial. An issue has arisen: After installing the Noty library (npm install no ...

What is the best way to include a variable or literal as a value in styled components?

When it comes to managing various use cases, I always rely on props. However, I am currently facing a challenge in changing the border color of a styled input during its focus state. Is there a way to utilize props for this specific scenario? Despite my f ...