Tips for ensuring an animation is triggered only after Angular has fully initialized

Within this demonstration, the use of the dashOffset property initiates the animation for the dash-offset.

For instance, upon entering a new percentage in the input field, the animation is activated. The code responsible for updating the dashOffset state is as follows:

  @Input({ transform: (p: string) => parseInt(p) })
  set percentage(p: number) {
    this.percentageState = p;
    if (!this.firstAnimation) {
      if (!!p) {
        this.dashOffset = this.calculateDashOffset(this.percentageState);
      } else {
        this.dashOffset = undefined;
      }
    }

If it is not the first animation, the calculation of the dashOffset state triggers the animation.

In case of the firstAnimation, the dashOffset state is established in ngAfterViewInit by the following:

  ngAfterViewInit() {
    if (this.firstAnimation) {
      this.dashOffset = this.calculateDashOffset(this.percentageState);
      this.firstAnimation = false;
      console.log(`The dash offset is ${this.dashOffset}`);
    }
  }

Nevertheless, this does not activate the animation initially.

In which stage of the component's lifecycle should we initialize an animation trigger to ensure that the first animation is initiated?

Answer №1

Here are a few steps you can take:

First, ensure that you have set

changeDetection: ChangeDetectionStrategy.OnPush
and push any changes like so:

svg-cicle.component.ts

  constructor(private ngz: NgZone, private changeRef: ChangeDetectorRef) {}

  private firstAnimation: boolean = true;
  ngAfterViewInit() {
    if (this.firstAnimation) {
          this.dashOffset = this.calculateDashOffset(this.percentageState);
          this.firstAnimation = false;
          this.changeRef.detectChanges();
    }
  }

Next, easily adjust the percentage in the main component which provides data to the circle itself:

main.ts

 ngOnInit() {
    this.control.valueChanges.subscribe((percent: any) => {
      console.log(percent);
      percent = parseInt(percent);

      percent = !!percent ? percent : 100;
      percent = isNaN(percent) ? 100 : percent;
      percent = percent < 0 ? 0 : percent;
      percent - percent > 100 ? 100 : percent;
      this.percentage = percent;
    });

    setTimeout(() => {
      this.percentage = 20;
    },1)
  }

The setTimeout function adds the change into a new render frame so that the animations work smoothly on start and whenever there is a change.

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 system is unable to locate the command "nvm"

Lately, I've been experimenting with using nvm to manage different versions of node. After successfully installing nvm on my Mac OS Catalina(10.15.6), I was able to easily switch between versions through the terminal. However, when attempting to do t ...

I am looking to enhance a button's appearance by applying CSS styling with a combination of two distinct flat colors

Is there a way to apply CSS styling to a button by incorporating two distinct flat colors? Specifically, I would like the left half of the button to be blue and the right half to be red. ...

Is there a way to effectively incorporate window.clearInterval() into this javascript code to achieve the desired outcome

In my quest to create a pomodoro clock, I decided to experiment with window.setInterval() and its counterpart window.clearInterval before delving into actual coding. However, I've encountered an issue with getting window.clearInterval() to function as ...

The firebase-generated observable is causing the notorious differ error as it is not iterable

Hey there, I'm encountering an issue that's preventing the route from rendering correctly. I initially thought that unwrapping an observable into an iterable using the async pipe would solve it, but this error indicates otherwise. Sometimes obser ...

Encountering build error ts2307 while using Angular 6 with npm: Module "ngx-loading-mask" not found

After exhausting all my search efforts on Google, I am stuck at a roadblock while upgrading from version 5.x to 6.x. My npm install runs smoothly with just 2 WARNS that are not causing any problems. But there are two strange issues that I can't seem ...

The console.log method is not functioning properly in the service

When developing my Angular application, I encountered an issue while creating a service. Here is the code snippet: @Injectable({ providedIn: 'root' }) export class PropertiesNameService { properties: string[] = []; constructor(p ...

Is there a way to dynamically update an image in my CSS without having to refresh the page?

Is it possible to update an image in CSS dynamically using the value of console.log without reloading the page? function reply_click(clicked_id){ $(function() { $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': ...

AngularJS ng-model directive binds an input field with a specific value

I encounter a challenge where my inputs, containing values, do not display the value when I apply an ng-model to each input field. Below is the snippet of my code: student-list.html <!--edit form--> <div class="col s12" ng-show="dataForm"> ...

Ignore missing values when performing an upsert operation

I'm currently utilizing pg-promise to manage my Postgres queries, but I've hit a roadblock with the following query conundrum: My goal is to develop a single method that can batch upsert multiple rows simultaneously. Here's the code snippet ...

Trouble arises when trying to combine NextJs 12.2.5 with next-auth 4.17 due to a dependency

npm ERROR! Could not find a solution for the dependency: npm ERROR! required peer next@"^12.2.5 || ^13" by [email protected] npm ERROR! in node_modules/next-auth npm ERROR! next-auth version is "*" as defined in the root project ...

What is the best way to pass and save information across different routes in Express using Node.js?

Let's delve into the specific functionalities I envision for my server. Essentially, my project involves user registration and login processes. The URLs for these routes are as follows - localhost:3000/login and localhost:3000/register Upon successf ...

What is the correct way to horizontally center a Material icon within a div?

How do I correctly center a Material Design icon within a div to fix the gap issue? I have tried using text-align on the items div, but it hasn't worked. (Refer to screenshots for clarification) @import url('https://fonts.googleapis.com/css2? ...

Struggling to dynamically append additional textboxes to a <div> element using JavaScript

After spending over 12 hours on this problem, I am completely stuck and frustrated. I have tried countless variations and sought out other solutions to no avail. It should be a simple task. My project involves using JQueryMobile 1.2 along with its dependen ...

Having trouble getting $.ajax to function properly in conjunction with fullcalendar js?

Currently in the process of utilizing the Smart Admin Theme, specifically focusing on the functionality within the calendar page. The calendar's core features are operational, allowing for the creation and placement of new events on the map. My curr ...

What is the best way to implement nested iterations in Jade?

ul li a(href='') menu1 li a(href='') menu2 ul li a(href='') sub-menu2 li a(href='') menu3 ul li a(href=&apos ...

Creating a CSS Box Along the Border of Another Box: A Step-by-Step Guide

Is there a way to render a box on another box's border, similar to the example image here: Expected Output I attempted using flexbox to achieve this, but unfortunately wasn't successful in finding a solution. If you have any advice or suggestio ...

Issue with Angular2 input not firing the change event

I am facing an issue where the (change) event is not triggered when updating an input field that is being updated from a query. Here is the HTML code for the input: <input type="text" [ngModel]="inputValue" id="itemText" (ngModelChange)="setNewItem($e ...

Tool to track character limits in multiple text fields

I'm facing a challenge with a form that includes 3 text areas, a copy button, and a reset button. My goal is to concatenate all the characters in the text areas to get a sum which will be displayed next to the copy/reset button. The character limit is ...

The state remains constant upon clicking

Below is the code snippet of my component: import React from "react"; import { useState } from "react"; import { Text, SvgContainer, Svg, Flex } from "../lib/styles"; import Modal from "./Modal"; const Credits = () ...

What is the best way to align these div elements within a table cell?

I am encountering an issue with the placement of elements. What I am striving for is something like this: https://i.stack.imgur.com/VSFXE.png where a div with several other divs inside is positioned at the top of the td, and another div is at the bottom o ...