How to use animation with Angular ?

ajayupreti

ajay upreti

Posted on July 31, 2021

How to use animation with Angular  ?

Introduction

Angular offers the ability to create powerful animations and activate them based on a variety of factors.

One of the changes from Angular 2 to 5 was the fact that they moved the animation functions from the angular core library, into their own animations library.

Initial Setup

Angular Animations are kept in their own module, so we need to import them into the module where they will be used.

import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

@NgModule({
  imports: [
    BrowserAnimationsModule
  ],
})
Enter fullscreen mode Exit fullscreen mode

Getting your component ready for animation

First, we need to import some animation functions to the top of the intended component:

import { trigger,state,style,transition,animate,keyframes } from '@angular/animations';
Enter fullscreen mode Exit fullscreen mode

Next, we have to add the animations property to the @Component() decorator:

  • The trigger animation function is the starting point of each unique Animation animation.
  • The first argument accepts the name of the animation, and the second argument accepts all of the other animation functions that we imported.
@Component({
  selector: 'app-root',
  template: `
  <p>I will animate</p>
  `,
  styles: [``],
  animations: [
    trigger('myAwesomeAnimation', [

    ]),
  ]
})
Enter fullscreen mode Exit fullscreen mode

Animation States and transitions

  • The state function allows you to define different states that you can call and transition between. The first argument accepts a unique name, and the second argument accepts the style function.


import { Component } from '@angular/core';

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
  animations: [
    trigger('popOverState', [
      state('show', style({
        opacity: 1
      })),
      state('hide',   style({
        opacity: 0
      })),
      transition('show => hide', animate('600ms ease-out')),
      transition('hide => show', animate('1000ms ease-in'))
    ])
  ]
})
export class PopOverComponent {
  show = false;
  constructor() { }

  get stateName() {
    return this.show ? 'show' : 'hide'
  }

  toggle() {
    this.show = !this.show;
  }
}
Enter fullscreen mode Exit fullscreen mode

In the HTML, we can now apply this animation to a div and provide a button to toggle the state between show and hide.

<div [@popOverState]="stateName">
        <p>Hello ! .</p>
</div>
<button (click)="toggle()">Toggle PopOver</button>
Enter fullscreen mode Exit fullscreen mode

Notice the comma after the trigger function,That's there so that you can define multiple animations, each with unique animation names defined within the first argument.

Multi-step animations with keyframes

What if you want to control the intermediate steps in an animation? That’s where keyframes come in.

Every keyframe has an offset ranging from 0.0 to 1.0, which represents its position in time relative to the animation duration. If an animation runs for 1000ms, a keyframe offset of 0.25 is equivalent to 250ms.

transition('void => *', [
        animate(1000, keyframes([
          style({ transform: 'translateX(-100px)', opacity: 0, offset: 0}),
          style({ transform: 'translateX(-50px)', opacity: 0.5, offset: 0.3 }),
          style({ transform: 'translateX(-20px)', opacity: 1, offset: 0.8 }),
          style({ transform: 'translateX(0px)', opacity: 1, offset: 1 })
        ]))
])
Enter fullscreen mode Exit fullscreen mode

Adding Animation callbacks

Sometimes you might want to trigger code when an animation is completed. In this example, we create an event handler to console log the animation start and done events.

logAnimation($event) {
  console.log(`${this.position} animation ${$event.phaseName}`)
}
Enter fullscreen mode Exit fullscreen mode

In the template, we can fire the event handler when the animation sends of the start and done events.

<div style="width: 100px; height: 100px"
        [@divState]="state"
        (@divState.start)="logAnimation($event)"
        (@divState.done)="logAnimation($event)">
</div>
Enter fullscreen mode Exit fullscreen mode

The callbacks receive an AnimationEvent that contains useful properties such as fromState, toState and totalTime.

This, in a nutshell, is how animations work in Angular.

💖 💪 🙅 🚩
ajayupreti
ajay upreti

Posted on July 31, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related