Creating Reusable Animations in Angular
In this article, we’ll re-create the Medium clap button by using Angular animations.
We’ll learn various animations features such as:
- Creating reusable animations (
animation
,useAnimation
) - State change expressions (
:enter
,:leave
,:increment
,:decrement
).
The article assumes a basic knowledge of the basic Angular animations methods, like trigger()
, transition()
, etc.
Understanding Reusable Animations
- Create an animation by calling the
animation()
function. It can contain a number of interpolated input parameters such as{{ timings }}
. - Consume the animation by calling the
useAnimation()
function. It accepts the animation reference as the first argument, and options object as the second. We pass in the input parameters under theparams
key. In this example we must provide the timings value:{ timings: 200 }
.
Now that we understand how to create reusable animations, let’s put it to use by creating the pulse animation.
Create the Pulse Animation
We create reusable pulse animation by calling the animation()
function. It accepts {{ timings }}
, and {{ scale }}
input parameters. The pulse animation is created by changing the element’s scale by calling the keyframes
function.
useAnimation(
pulseAnimation,
{ params: { timings: 200, scale: 1.1, } }
)at 0ms scale equals 1
at 100ms scale equals 1.1
at 200ms scale equals 1
Next, we’ll consume the animation inside our first component.
Create the FAB Component
Inside the component’s animations array, we call the trigger()
function with a descriptive counterChange
name.
Next we define a transition, and use :increment
as the state transition expression. It is a perfect fit, as we want to perform the animation when the user taps on the button, incrementing the claps counter.
Understanding State Change Expressions
:increment
— the binding is incremented
:decrement
— the binding is decremented
:leave
— the element is removed from the DOM.
:enter
— the element enters the DOM.
Create the Slide Animation
Just as in the pulse
animations, we use the animation()
function to create reusable animations. Like before, we use interpolation to define the animation input parameters.
Create the Bubble Component
As the parent component displays and hides the bubble component, we want to trigger the slide in and out animations. This is a perfect place to use the :enter
and :leave
state change expressions.
We consume the slide animations created in a previous step by calling the useAnimation()
function with the appropriate input parameters.
Summary
And that’s it. Hope you enjoyed this article. We’ve used a lot of impressive features from Angular Animations to recreate the Medium Clap Button. You can find the complete code examples below.