Ciprian Craciun - FrontEnd Developer

Ciprian Craciun

FrontEnd/Web Developer

Engineering is about making a product better, learning from past mistakes and create a process which is easy for all to understand.

How to create and use angular animations ?

If you are working with angular, there will be a time when you need to create animations. In this case, you need to know a few things before diving into this part of animations, by the end of this article I hope you will have a good understanding of:

Start over with angular animations

As we know we can create animations in CSS, by default CSS can provide us some basic rules for animations: animation property combined with @keyframes. We can add animation-name, animation-duration, animation-delay and other configurations. We can choose to combine our animation with CSS3 rules to create more complex animations, but if we don’t want to write animations then we can use animate.css which provide more custom effects.

p {
  animation-duration: 3s;
  animation-name: slidein;
}
@keyframes slidein {
  from {
    margin-left: 100%;
    width: 300%;
  }
  to {
    margin-left: 0%;
    width: 100%;
  }
}

More information about CSS animations you can find on MDN web docs: Using CSS Animations. Either way, we can create animations combining javascript with css, head to the w3schools to see more examples.

How we add animations in angular ?

From the start, Angular has a module for animations, @angular/animations this module we have helper functions that can provide flexibility in terms of creating animations in angular. Let’s start by creating a basic example and take it line by line:

import {
  trigger,
  state,
  style,
  animate,
  transition,
  // ...
} from '@angular/animations';
@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.css'],
  animations: [
    // animation triggers go here
  ]
})

As we can see, the first time we added the required imports, then in the component decorator we are adding the parameter. Here is the place where the code for animations will be placed. We will see later how to group our animations in one place and then how we can reuse them.

To work with animations you need also to know how to use states, they are steps for your cool effect. Angular provides 3 ways of defining states:

1. Void state – this is happening when an element is created but is not placed into DOM yet. We define this with the keyword void
2. The wildcard state – is the default state of the element, to define this state in our code we use the * symbol.
3. Custom state – we need to define the name of the state in the code

Angular states
Angular States

A simple example of using state:

animations: [
  trigger("fade", [
    state("void", style({ opacity: 0 })),
    transition("void => *, * => void", [animate(2000)])
  ])
];

Now because we use steps from states, we use the short version of them which makes the code more clear:

1. 'void => *' - :enter
2. '* => void' - :leave

In this case, we can write our animation like:

animations: [
  trigger("fade", [
    state("void", style({ opacity: 0 })),
    transition(":enter, :leave", [animate(2000)])
  ])
];

After you defined the states the next step is to create your custom animation using transition and animate .

Group your animations

Why do we want to group our animations? Let’s say that we want to create the fade effect and we use it in the app component, then we see that we have the same effect in a sidebar component. In this case a better approach is to create the fade animation once and use it in multiple places.

For example, I’m creating animations in animations.ts a file like this:

import { animation, animate, style, group } from "@angular/animations";
export const slideInAnimation = animation([
  style({
    transform: "{{ styleTransform }}",
    overflow: "{{ overflow }}",
    opacity: 0
  }),
  animate(
    "{{ time }}",
    style({
      transform: "{{ animateTransform }}",
      opacity: 1
    })
  )
]);

In the component this animation is used:

import { trigger, transition, useAnimation } from '@angular/animations';
import { slideInAnimation } from '../../utils/animations';
trigger('slideWithFade', [
      transition(':enter', [
        useAnimation(slideInAnimation, {
          params: {
            styleTransform: 'translateX(100%)',
            animateTransform: 'translateX(0%)',
            overflow: 'hidden',
            time: '300ms ease-out'
          }
        })
      ]),
      transition(':leave', [
        // other animation
      ])
    ])
  ]

Add animations created to HTML elements

Now that we created the animations we apply them to HTML elements with the alias @slideWithFade

<div class="list-group" @slideWithFade></div> 

In a conclusion, if you have generic animations and you think that they would be used in multiple places, the best approach is to have a separate file where you can add as many animations as you want. Don’t create duplicate code.

You may be interested to read some other articles from my Blog:
1. How to structure a node js application
2. React native maps for Android
3. How to use redux persist with react native

Sharing is caring!


Leave a Reply

Your email address will not be published. Required fields are marked *