Animations in Angular


Introduction

Animations are a powerful way of capturing user's attention. HTML elements can shrink or grow in size, rotate in different axis, fade, move from one position to other, change in different CSS styles depending on the applied animation. Transformations on HTML elements can make our application more interactive and interesting. We can even set the timing for each animation depending on our requirements. Animations are transitions from one state to another. The motion of HTML elements enhances our application's UI. 
  • Animations can be applied one by one or simultaneously. 
  • User actions with different animations make our UI looks more fun. If we click a button and some animation starts, it will be more noticeable by the user.
  • Transformations include position, color, sizes, rotation, etc. CSS properties are used for transition.

Applying Animations To Project

In Angular, we need to import @angular/animations package using the NPM command as they are part of the animation package. The below command will save the package in package.json also as we have used --save. After this, we need to import BrowserAnimationsModule in the app.module.ts file.

npm i @angular/animations@latest --save

Now import BrowserAnimationsModule as follows:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';

@NgModule({
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    FormsModule,
    ReactiveFormsModule
  ],
  declarations: [
   AppComponent
 ],
  bootstrap: [ ]
})
export class AppModule { }

Now we will go app.component.html file and start writing animation. The first thing is we need to import some of the animation functions from @angular/animations. Functions are such as trigger, state, style, transition, animate and keyframes. Keyframes are used for sequential animation. All the function is required to apply any animation to accept keyframes.

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

Now we will apply animations metadata in our component decorator. Animation definition linked to our respective components with this animation property only. We will now use the above functions one by one.

  • trigger() - It is used to start off the animation. The first argument is the animation trigger name. We will use this name in our HTML template to apply the animation. It is used as a container to write all other animation functions. Uses array syntax.
  • state() - It is a named set of CSS properties that can be applied during animation change from one state to another. We can have a name for the states which can be used in different animation functions also. 
  • style() - It is a set of CSS properties or transforms functions that are used in animation. Uses object syntax.
  • animate() - It specifies the time for each transition in an animation. Optional values for this function are delay time and easing. It can even contain style() calls. 
  • transition() - It defines the change from one state to another. Uses array syntax.
  • keyframes() - It is written in animate() function. Used for multistep animation. Each keyframe can have multiple styles. Uses array syntax.
Now we will define an animation that will use the above functions.

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.css'],
  animations: [
    // animation definition written here
  ]
})

Let us write a simple animation in which we will have two states 'open' and 'close'. In open state, we will have some properties and in the closed state, we will have another set of CSS properties. We will change the color also in different states.

State and Style

We can define the state of the animation which we will define in the transition function. The first argument to state function is the unique name for that state and the second argument is the style() function. We need to define the CSS styles in this style() function that corresponds to each state. We need to use camelCase for the CSS properties inside the style() function. background-color becomes backgroundColor. In our style function, we are using transform property. 

Triggering the Animation

It is used to start off the animation. The first argument is the animation trigger name. We will use this name in our HTML template to apply the animation. It is used as a container to write all other animation functions. Uses array syntax. We need to link the myAnimation to the HTML element to trigger the animation. Multiple triggers can be active at one point in time. myAnimation is the property name that watches for transformations.

<div [@myAnimation]="some expression"></div>

Now we will see how different states are defined using style() function.
@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.css'],
  animations: [
   trigger('myAnimation',[

     state('small', style({
        transform: scale(2),
        backgroundColor: red,
        
      })),
      state('large', style({
        transform: scale(4),
        backgroundColor: blue,

      })),
  ]
  ]
})

Transition and Animate function 

Transition function is used to define the change from one state to another. The first argument of transition() defines the direction change from one state to another. An animation will have only one state at a given point in time. The second argument is animate() steps.
The animate () function has duration, delay and easing parameters. The syntax is
animate(' duration delay easing'). The duration and delay can be in seconds or milliseconds. The third parameter easing defines how our animation runs. 
ease-in, ease-out, ease-in-out are the possible values.

transition('small => large', [
  animate('1s 0.1ms ease-in-out')
]),

Now we will apply the above animation on a <div> tag.


@Component({
  selector: 'app-root',
  template:`<div [@myAnimation]="onState" (click)="animationFn()"></div>`,
  styleUrls: ['app.component.css'],

  animations: [
   trigger('myAnimation',[
     state('small', style({
        transform: scale(2),
        backgroundColor: red,
      })),

      state('large', style({
        transform: scale(4),
        backgroundColor: blue,
      })),

      transition('small => large', [
        animate('1s, ease-in-out')
      ]),

      transition('large => small, [
        animate('0.5s, ease-out')
      ]),
  ])
]

})
export class AppComponent {
  onState:string  = 'small';

animationFn(){
 this.onState = ( this.onState===small ? 'large' : 'small');
} 

}

Using Keyframes 

It is written in the animate() function. Used for multistep animation. Each keyframe can have multiple styles. Keyframes are written using various CSS styles using style() function. We can have multiple style() function calls within the keyframes. See the below example in which we implemented keyframes within the animate() function. Use style() function calls for writing CSS properties.


@Component({
  selector: 'app-root',
  template:`
<div [@myAnimation]="onState" (click)="animationFn()"></div>
`,
  styleUrls: ['app.component.css'],
  animations: [
   trigger('myAnimation',[
     state('small', style({
        transform: scale(2),
        backgroundColor: red,
      })),

      state('large', style({
        transform: scale(4),
        backgroundColor: blue,
      })),

      transition('small => large', animate('1s, ease-in-out',keyframes([
       style({ opacity:0, transform: rotate(90deg),offset:0}),
       style({ opacity:1, transform: rotate(180deg),offset:0.5}),
       style({ opacity:1, transform: rotate(0deg),offset:1}),
      ]))),
     
  ])
]
})
export class AppComponent {
  onState:string  = 'small';

animationFn(){
 this.onState = ( this.onState===small ? 'large' : 'small');
} 
}

Comments

  1. Nice blog. Can you please give more examples of angular animation.

    ReplyDelete

Post a Comment