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

Are third-party scripts and HTML widgets able to replicate your website's data, including cookies, HTML, and other elements?

Currently, I am in the process of constructing a website that incorporates a third-party weather HTML widget. The widget is sourced from a trusted and reliable source on the web. It consists of a link and small JavaScript tags that are executed once loaded ...

Node.js is throwing an error stating that it cannot read the property 'id' of a null value

I have been working on upgrading my old Discord bot from Node.js version 6.x.x to 8.x.x and organizing the commands in a separate folder for better organization. The command was functioning properly with my old bot, but it seems to be encountering issues w ...

jQuery Waypoints Error: The sticky functionality is missing and cannot be utilized in this context

Trying to anchor an element at the top of a WordPress page using the jQuery Waypoints plugin. <script src="path/to/waypoints.min.js"></script> <script> $('#myelement').waypoint('sticky'); </script> However, t ...

Getting the environment variable from Rails in your JavaScript: A guide

I am currently working on implementing a key system within my application. In the code I am using, there is logic that looks like this: $('.key-test-button').on('click', function(){ if ($('.key-test-input').val() === "MYK ...

What is the best way to enter text into the terminal following the execution of "yarn start"?

While developing a Node chat application, I encountered an issue where I am unable to type anything in the terminal after entering "yarn start". The tutorial I am following shows that the instructor can still input commands in their terminal after running ...

What is the best method to assign a property to a model within AngularJS by utilizing an attribute parameter?

I am in the process of creating a custom directive in AngularJS for a UI slider that can be used multiple times. Each slider should be able to bind to a specific property. My idea was to use an attribute called "property" which would automatically update w ...

A step-by-step guide on creating a unique ticket number sequence in PHP

Looking to create a unique ticket number sequence using PHP? Here's the given sequence: 1-W1 (mandatory). 2-Date (yy-dd-mm) format. 3-001-999 (resets daily from 001). Check out this example: e.g. - W120200101001 I've started the code below, b ...

Challenges with Displaying Filtered Arrays in Angular

Currently, I am working through a tutorial and have hit a snag in a particular feature. The task at hand is to display a filtered array (which comes from firebase) when clicking on an anchor. Despite following all the necessary implementation steps, I seem ...

An error was encountered when attempting to reference an external JavaScript script in the document

Could someone please provide guidance on how to utilize the document method in an external .js file within Visual Studio Code? This is what I have tried so far: I have created an index.html file: <!DOCTYPE html> <html lang="en"> <head> ...

Troubleshooting the issue with UI-Router AngularJS controller not functioning properly in a

Trying to grasp the ins and outs of UI-Router in conjunction with Angular has proven to be quite challenging for me. In my setup, there's an index: <body> <div ui-view></div> <!--Location of file holding app--> <scri ...

Leveraging event listeners in conjunction with React's useEffect function

Check out the code example on Code Sandbox here Hey there, I'm trying to implement a feature where clicking a button inside a container displays a box. I've set up an event listener so that when you move your mouse outside the container, the box ...

The issue of jQuery, Ajax, and MVC6 parameters becoming null after an Ajax request has been identified

Hello everyone, I am a beginner in asp.net core, c# and MVC 6. Currently, I am facing an issue with sending data over ajax to my controller. function sendAjaxData() { $.ajax({ url: "AjaxWithData", // using hardcoded value for testing purpose type ...

Pagination with React Material UI is a user-friendly and visually

Requirement Within the Material UI framework, I need to implement pagination functionality by clicking on the page numbers (e.g., 1, 2) to make an API call with a limit of 10 and an offset incrementing from 10 after the initial call. https://i.stack.imgur. ...

"Troubleshooting the failure of the alert function to work properly when loading content

I am working on a webpage named index.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Co ...

No content in Axios response

axios.post( 'http://localhost:3001/users', { username:user.username } ).then((res)=> console.log(res.data)) Response From FrontEnd : data: &qu ...

What is the best way to place a 3D model at random points on the surface of a sphere while ensuring that it always faces the right direction?

I'm faced with the challenge of placing huts randomly on a spherical world. While this task is feasible, the issue arises when the huts do not sit correctly - their bottom should be in contact with the tile below. I've experimented with the &apos ...

When I test my jQuery scripts in jsfiddle, they run smoothly. However, they do not seem to work properly when I

My code is almost perfect, but the jQuery function is giving me trouble. It works fine in jsfiddle, but for some reason, it's not functioning in my HTML file. I don't believe extra characters are being added when copying from the HTML file. I hav ...

Tips for adding a border to a table cell without disrupting the overall structure of the table

Looking for a way to dynamically apply borders to cells in my ng table without messing up the alignment. I've tried adjusting cell width, but what I really want is to keep the cells' sizes intact while adding an inner border. Here's the sim ...

Unable to set a JSON data as a value for a JavaScript variable

I am currently developing a YT mp3 downloader using the API provided by youtubeinmp3. I have been successful in obtaining the download link in JSON format. https://i.stack.imgur.com/3mxF2.png To assign the value of "link" from the JSON to a JavaScript va ...

Having difficulty updating the parent for all PortfolioItem/Feature that were copied for a specific PortfolioItem/MMF

I'm facing a challenge in setting the parent for multiple features that I've copied for a specific MMF. However, only the parent of the last feature is being set. Below is the code snippet responsible for setting the parent: Record represents th ...