In Angular 20.2, CSS animations for transitions have evolved with a fairly simple API.
Let’s dive into it.
How to animate a new element entering the screen?
Here is an example of animation for an element entering the screen:
The first thing to know is that animations are 100% driven by CSS. If you’re not familiar with CSS animations, you can use the CSS animation generator mentioned in this post.
Note that AI tools can also assist you in generating proper CSS animations. In the case of the example above, I used the following CSS code:
.entering {
animation: slide-fade 2s;
}@keyframes slide-fade {
from {
opacity: 0;
transform: translateY(30px);
}
to {
opacity: 1;
transform: translateY(0);
}
The code is almost self-explanatory: We transition from an opacity of 0 (invisible) 30 pixels from the bottom to an opacity of 1 (fully visible) at the right position, and this animation lasts for 2 seconds.
Once the CSS class is ready, all that is left to do is tell Angular to use it. Here is how:
That’s it! animate.enter is a specific attribute supported by the Angular compiler. It’s not a directive, which means no import needed. You can use it as-is.
How to animate a new element exiting the screen?
Another attribute called animate.leave can be added as well.
Let’s create another transition to use when hiding the element:
.leaving {
opacity: 0;
transform: translateX(20px);
transition: opacity 500ms ease-out, transform 500ms ease-out;
}
This one moves to the side by 20 pixels and lasts 500 ms. We apply it by adding animate.leave to our element:
animate.enter="entering"
animate.leave="leaving">I'm animated!
My name is Alain Chautard. I am a Google Developer Expert in Angular and a consultant and trainer at Angular Training, where I help web development teams learn and become proficient with Angular / React / JavaScript.
If you need any help learning web technologies, feel free to get in touch!
If you enjoyed this article, please clap for it or share it. Your help is always appreciated. You can also subscribe to my articles and Weekly Angular Newsletter to receive helpful weekly tips and updates about Angular.