If the variable state is modified using setInterval, Angular animations will not function as intended

I am attempting to create an animation that changes the opacity of three arrows (intended for user interaction on my website). To achieve this automatically and repeatedly upon loading the webpage, I have implemented a setInterval function within ngOnInit. While this method successfully alters the variable state, I have noticed that the animation only functions properly when triggered by an event like (click)="showArrows" as opposed to setInterval.

@Component({
  selector: 'app-photo-and-name',
  templateUrl: './photo-and-name.component.html',
  styleUrls: ['./photo-and-name.component.css'],
  animations: [
    trigger('animateArrows', [
      state('inactive', style({
        opacity: '1'
      })),
      state('active', style({
        opacity: '0.5',
      })),
      transition('inactive => active', animate('400ms ease-in')),
      transition('active => inactive', animate('400ms ease-in'))
    ])
  ]
})
export class PhotoAndNameComponent implements OnInit {
  arrowsState: string = 'inactive';
  interval: any;

  constructor() { }

  ngOnInit(): void {
    this.interval = setInterval(this.showArrows, 2000);
  }

  showArrows() {
    this.arrowsState = this.arrowsState === 'active' ? 'inactive' : 'active';
    console.log(this.arrowsState);
  }
}
<div class="arrows" [@animateArrows]="arrowsState">
    <mat-icon class="arrow">arrow_drop_down</mat-icon>
    <mat-icon class="arrow">arrow_drop_down</mat-icon>
    <mat-icon class="arrow">arrow_drop_down</mat-icon>
</div>

Why does the animation not work with setInterval and what alternative approach should be taken?

Answer №1

In situations like this, consider utilizing CSS animation with a class instead of relying on Angular animation. Angular animations are more suitable for scenarios involving dynamic state changes triggered by events such as page loading or button clicks.

For repetitive tasks, CSS offers superior options to accomplish the desired functionality.

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

Looking to perform an Ajax call to update a Rails model using HTML5 contenteditable, but encountering an issue where it creates a new

I am in need of assistance to update the plots of a story using HTML5 contenteditable feature. Below is the code snippet: Refer to file# for editing multiple plots <div id="editable" contenteditable="true"> <%= simple_format p.description %&g ...

`How can I stop typescript from converting dynamic imports to require()?`

Currently, I am in the process of creating a Discord bot using discord.js. Interestingly, discord.js does not seem to be compatible with ESM modules, which has been causing some complications in my project. As a result, I have resorted to utilizing CommonJ ...

Converting SVG to PNG image directly in the browser (compatible with all browsers, including Internet Explorer)

I am currently working with Highcharts and I have a need to convert all the charts displayed on the webpage into images so that I can send them to my server for merging with a master export Excel file. The Excel file already contains some tables and pivot ...

Error Encountered on Android Due to Sec-WebSocket-Key Mismatch

I'm facing an issue with my WebSocket implementation using PHP. It seems to work fine on my desktop computer, but when I try to access my website on an Android device, the server implementation throws an error during the handshake process. It shows ...

What is the process for inserting a new column into an order list on Opencart?

I'm looking to customize the table in opencart's admin dashboard by adding a new column for 'company name' between 'Customer' and 'Status'. Can anyone guide me on how to achieve this? Which specific file do I need t ...

The error message "window is not defined in Angular Universal" indicates that the window object

While attempting to utilize @nguniversal/express-engine, I encountered an issue in the main.js file after installing and running it. The error message reads: C:\Folder\ssr\dist\ssr\server\main.js:179450 })(window, functio ...

What is the method to advance the opposing line in the dynamic chart?

Here is the link to the code for a dynamic graph. I am struggling with keeping the red line updated and moving forward together with the blue line. I cannot figure out why the red line remains static in the dynamic graph. Any suggestions on how to solve t ...

What is the best way to add a bottom border to each row in a textarea?

I am currently exploring methods to include a border-bottom line for each row in a <textarea>, but so far I have only been able to achieve this on the very bottom row. Is there any way to make this happen? .input-borderless { width: 80%; bord ...

Are you looking for routes that lead to the edit page?

Is it possible to target routes that end with 'edit' using express.js? For example, I have the following normal routes: app.get('/one', controller.one); app.get('/two', controller.two); I want to know if it's possible ...

Safeguard your Electron app's contents from theft

As I embark on creating an Electron app, my main concern is ensuring that the content - which consists of various mp3/png/svg files - remains exclusive to the app. It seems challenging to prevent users from accessing these files outside of the application, ...

finding the index of a particular checkbox in a list

I am working with a list of checkboxes that are dynamically created using JavaScript, each contained within its own separate div element. I need to determine the position number of a specific checkbox within all checkboxes sharing the same class within a p ...

Guide to managing AutoComplete {onChange} in MUI version 5 with a personalized hook

Currently, I am utilizing a custom hook that manages the validation and handling of the onChange function. For most components like input, select, and textField, I have no trouble with handling the onChange event using the syntax below: The code snippet ...

Having difficulty navigating the features of the rxjs `merge` interface

Having trouble with the RxJs merge interface: export function merge<A extends readonly unknown[]>(...sources: [...ObservableInputTuple<A>]): Observable<A[number]>; So, based on this information, I developed the following code const alpha ...

display upcoming schedule and time

How can I display the future date and time in the respective field components? See below for a sample code snippet: require([ "dojo/_base/lang", "dijit/registry", "dojo/ready", "dijit/form/TimeTextBox", "dojo/parser" ], function(lang, registry, ready ...

Interact with HTML Radio Buttons to Trigger Input Opening

I need to have a message saying "We're sorry..." and a "black box" displayed only when the radio button is set to YES, otherwise keep it hidden. Can I achieve this using JavaScript only, or is there a way to do it with HTML alone? <h3 >Did you ...

What is the meaning of MVVM "binder" and how is it used?

I've been conducting research online to gain a deeper understanding of the MVVM architecture in general. According to Wikipedia, the key components of the MVVM pattern are: Model View View Model Binder This is the first time I have come across the ...

Tips on dynamically naming form controls based on user input

I am working on creating a JSON object using Angular 8 forms, where the control name will be defined by the user through a text input field. This control will contain formArrays of unit and price elements, allowing users to add as many unit-price combinati ...

"Encountered a syntax error while attempting to reference an attribute on an empty object

> "[object Number]" === Object.prototype.toString.call(1) // #1 < true > "[object Number]" === {}.toString.call(1) // #2 < true > {}.toString.call(1) === "[object Number]" // #3 < SyntaxError: Unexpected token ...

Why is the refresh endpoint generating new tokens when an outdated refresh token is used?

Greetings! I am currently utilizing two npm libraries, namely bcrypt and jsonwebtoken. I have implemented an endpoint called /refresh-token wherein I aim to generate a new set of access and refresh tokens. The process involves sending the refresh token to ...

Checking email existence through remote jQuery validation

Utilizing the jQuery validator plugin, I am implementing an ajax function with a remote method to validate whether an email already exists in my database. However, I am encountering an error when making the ajax call within my validation function. "email ...