How to implement an Angular Animation that is customizable with an @Input() parameter?

Have you ever wondered if it's possible to integrate custom parameters into an Angular animation by passing them through a function, and then proceed to use the resulting animation in a component?

To exemplify this concept, consider this demo where the animation is defined separately in animations.ts as shown below:

import {
  trigger,
  state,
  style,
  transition,
  animate,
  group,
} from '@angular/animations';

export const SlideInOutAnimation = [
  trigger('slideInOut', [
    state(
      'in',
      style({
        width: '50%',
        opacity: '1',
        visibility: 'visible',
      })
    ),
    state(
      'out',
      style({
        width: '50px',
        opacity: 0.3,
        visibility: 'visible',
      })
    ),
    transition('in => out', [
      group([
        animate(
          '600ms ease-in-out',
          style({
            width: '50px',
          })
        ),
      ]),
    ]),
    transition('out => in', [
      group([
        animate(
          '1ms ease-in-out',
          style({
            visibility: 'visible',
          })
        ),
        animate(
          '600ms ease-in-out',
          style({
            width: '50%',
          })
        ),
        animate(
          '800ms ease-in-out',
          style({
            opacity: '1',
          })
        ),
      ]),
    ]),
  ]),
];

The next step involves importing and utilizing this animation within a component by declaring it in the animations property of the @Component decorator.

However, what happens when we need to incorporate an @Input property value and utilize it within the animation?

For instance, if we have something like:

@Input()
width: 50%;

How can we transmit this parameter to the animation effectively?

Answer №1

Working with animated "parameters" doesn't have to be challenging.

Just picture something straightforward.

animations:[
    trigger('custom',[
      transition('*=>*', [
        style({ width: `{{width}}`  }),
        animate('500ms ease-in', style({ width: `100%`  })),
      ],{params:{ width: "0"}}),
    ])
 ]

We define the "parameters" within the "params" (as an object) and when using them, they are enclosed in {{ }}.

It's important to specify a default parameter.

Then, when defining the animation in the .html file, we pass the parameters. For example, if you have variables for "value" and "width", your html can look like:

<div class="header" [@custom]="{value:value,params:{width:width}}" >

Subsequently, when we alter the "value", the animation will trigger

<button (click)="width='50%';value=!value">width:50%</button>
<button (click)="width='0';value=!value">width:0</button>

Check out stackblitz

In the Stackblitz demo, a variable is used in the component, but you can also utilize an Input. Remember, if you wish for the animation to commence, you must modify the "value" (unless utilizing :enter and :leave).

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

Tips for animating input width as the size value changes during an ajax query transformation

This is my JavaScript code: function updatePriceDisplay() { $.ajax({ url:"query.php?currency=<?=$currencycode;?>" }).done(function(data) { $("value").attr("value", data).attr("size", data.length - 2); }); } updatePriceDi ...

Find the value of a JavaScript string variable using an alternative name

My latest JavaScript function is designed to fetch JSON data from either a server or local files on any browser. This piece of code processes JSON from two sources: an XMLHttpRequest response, or a variable imported via script. In the case of the latter, ...

The React hook useState is struggling to accurately map array objects

Recently, I encountered an issue with a form that sends an array of objects to another React Functional Component: import React, { useState } from 'react' import uuid from 'uuid/v1'; const NewMovieForm = ( {addMovie }) => ...

Encountered an issue while attempting to retrieve the access token from Azure using JavaScript, as the response data could

Seeking an Access token for my registered application on Azure, I decided to write some code to interact with the REST API. Here is the code snippet: <html> <head> <title>Test</title> <script src="https://ajax.google ...

Deciphering the occurrence of jQuery-Mobile page firing events: the mystery behind dialog pages appearing upon closure

I'm still fairly new to jQuery-Mobile and I'm trying to wrap my head around what exactly happens when a page or dialog is loaded. To help illustrate the confusion I'm experiencing, I put together a small collection of files that showcase th ...

Guide on transferring three js variable to an HTML label element

For my project, I am looking to pass three js values to the label of a div. The desired output is: stWay: stProposer: stTime: hello John 2017-09-07 I have successfully programmed a button to make div1 a ...

Understanding the visibility scope in JavaScript's object-oriented programming

I have the following code snippet: function A() { this.AFunction = function() { var b = new B(); b.BFunction(); } } function B() { this.BFunction = function() { // some code $.ajax({ url: url suc ...

Ways to maneuver the vehicle by using the left or right key inputs

I am a beginner with canvas and game development. I am currently working on a project where a car moves in a straight line, but I want to add functionality for the car to turn anti-clockwise when the left key is pressed, and clockwise when the right key is ...

Loading a specific CSS file along with an HTML document

Creating a responsive website, I'm looking to incorporate a feature that allows for switching between a mobile version and a standard desktop version similar to what Wikipedia does. To achieve this, I would need to reload the current HTML file but en ...

Updating div with specific class based on selected values

I have utilized Angular to display content based on selected values from a dropdown menu. Now, I am seeking a solution to dynamically add a CSS class to a div when specific values are chosen. In other words, I want to apply certain styling to the div base ...

How can you stop data URI from being cached as an image source?

I am facing an issue where I have an img-tag with a data-image base64 URI as the source. Browsers tend to cache this source, which is causing problems for me. If it were a normal URL, I could easily prevent caching by adding a random query-parameter value. ...

Angular Reactive Forms: Implementing Error Display and Red Border Styling

Recently, I've started diving into Angular Reactive Forms and I'm quite impressed by the async validator feature for tasks that involve checking data against a database. The separation of validation rules from the GUI is also very appealing to me ...

Executing a Drupal rule using JavaScript: A step-by-step guide

I'm facing a challenge when trying to activate a Drupal rule using JavaScript code. lowerLayer[image.feature_nid].on("dragend", function() { var position = kineticImage.getPosition(); var layerPosition = this.getPo ...

Concealed Input Enhancements for AutoComplete

Hey there! I'm new to AJAX and could really use some help with my autocomplete function. I'm trying to store the ID of the user's selection in a hidden input field, but I've hit a roadblock. So far, my function isn't working as exp ...

A step-by-step guide on incorporating a .env file into a React JS project that is written with TypeScript

I'm currently working on a React JS project with TypeScript. I know that we can utilize a .env file to define some configurations, like so: .env file REACT_APP_SOME_CONFIGURATION = "some value" We can then use these configurations in our c ...

Ever since I switched to a different monitor, my Javascript has suddenly stopped functioning

I'm encountering an issue where my JS stops working every time I switch displays within a single HTML file. I've attempted to replace the HTML onclick call with a JavaScript function, but the problem persists. Update: Apologies for the unclear e ...

Utilizing lodash to Filter Arrays Within Arrays

Let's take a look at the JSON structure provided below. comapany : ABC Emp Info:[ { empName: D, empID:4 salary[ { year: 2017, ...

What is the process for bringing in AngularJS 2? // Bring in { routerTransition } from './router.module;

Currently, I'm experimenting with implementing page transitions using Angular 2. The resources I've gone through indicate that I need to import: // import { routerTransition } from './router.module; However, despite following these instruc ...

Troubleshooting $digest problems with AngularJS and the selectize directive

I am encountering difficulties when utilizing the watch function within a directive in conjunction with a third-party plugin named selectize. Despite researching extensively about $digest and $watch, I am still facing issues. Although my example below is ...

Run a series of functions with arguments to be executed sequentially upon the successful completion of an ajax request

I am currently working on implementing a couple of jQuery functions to assist me in testing some api endpoints that I am developing in php. While I have limited experience with Javascript and jQuery, I am struggling to figure out what additional knowledge ...