AppDividend
Latest Code Tutorials

Angular Animations: How to Use Angular 10 Animation

0

Animations, in general, provide the illusion of motion: HTML elements change styling over time. Animations in Angular can improve your app and user experience in several ways:

  1. Without using animations, web page transitions can seem abrupt and jarring.

  2. Motion drastically enhances the user experience, so animations give users the chance to detect the application’s response to their actions.

  3. Good animations intuitively call a user’s attention to where it is needed.

Angular 10 Animations

Animations involve multiple style transformations over time. It includes element moving, changes in color, growing or shrinking of components, fade, or slide off the page. These changes can occur concurrently or sequentially. You can control the timing of every transformation.

The animation is defined as a transition from the initial state to a final state. It is an integral part of modern web applications. Angular empowers us to create animations that provide us similar native performances as CSS animations.

Understanding Angular Animation States

Animation in Angular involves a transition from one state of the element to another state. Angular defines three different states for a component:

Void State

The void state represents a state of the element that is not part of the DOM. This state occurs when the element is created but not yet placed in the DOM, or the element is removed from the DOM.

Wildcard State

The wildcard is also known as the default state of the element. The styles defined for this state apply to the component regardless of its current animation state. To determine this state in our code, we use the * symbol.

Custom State

The custom state needs to be defined explicitly in the code. To define the custom state, we can use any custom name of our choice.

Angular Animation Transition Timing

To display the animation transition in Angular from one state to another, we define animation transition timing in our application.

Angular provides the three-timing properties, which are as follows.

Duration

The Duration in Angular describes the time our animation takes to complete from the start (initial state) to finish (final state).

We can define the duration of angular animation in the following three ways.

  1. Using an integer value to describe the time in milliseconds. E.g., 1000.
  2. Using the string value to describe the time in milliseconds. E.g.: ‘1000ms’.
  3. Using the string value to describe the time in seconds. E.g.: ‘1s’.

Delay

The Delay in Angular represents the duration between the animation trigger and the beginning of the actual transition. The Delay property follows the same syntax as duration property.

To define a delay in Angular, add the delay value after the duration value in a string format: ‘Duration Delay’. Delay is an optional property.

Easing

Easing property in Angular represents how the animation accelerates or decelerates during its execution.

To define the easing in Angular, add the third variable in the string after the duration and delay properties.

If the delay value is not present in the function, then easing will be the second value. The easing is also an optional property.

Prerequisites

Install Visual Studio Code and Angular CLI.

If you are a beginner in Angular 10, then refer to one of my previous articles Angular 10 Tutorial to set up the Angular 10 development environment on your machine.

Getting started with Angular Animations

To get started with adding Angular animations in your project, import the animation-specific modules along with the standard Angular functionality.

Step 1: Creating the Angular 10 application

To create an Angular 10 project, type the following command.

ng new anganimation

Also, install Bootstrap 4 using the following command.

npm install bootstrap

Open an Angular.json file and add the path to the Bootstrap CSS Framework.

"styles": [
  "src/styles.css",
   "./node_modules/bootstrap/dist/css/bootstrap.min.css"
],

Now, go inside the folder and open a folder in VS Code using the following command.

code .

Step 2: Enabling the animations module

Import BrowserAnimationsModule that introduces the animation capabilities into your Angular root application module.

Write the following code inside the app.module.ts file.

// app.module.ts

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

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

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

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

Step 3: Importing animation functions

If you plan to use particular animation functions in component files, import those functions from @angular/animations. In our case, it is the app.component.ts file.

// app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  ngOnInit(): void {
  }
}

These functions trigger, state, style, animate, and transition are defined in the @angular/animations module. So, we need to import the animations module in our component.

Step 4: Adding the animation metadata property

In the app.component.ts file, add the metadata property called animations: within the @Component() decorator. You put the trigger that defines animation within the animations metadata property.

// app.component.ts

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

Understanding the Angular Animation Syntax

We will write the animation code inside the component’s metadata. See the following syntax.

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  animations: [
    trigger('triggerName'), [
      state('stateName', style())
      transition('stateChangeExpression', [Animation Steps])
    ]
  ]
})

Here we will use the property called animations, which will take the array as input. The array contains one or more “trigger”. Each trigger has the unique name and the implementation. The state and transitions for our animation need to be defined in a trigger implementation.

Each state function has the “stateName” defined to uniquely identify the state and a style function to display the style of the element in that state.

Each transition function has the stateChangeExpression defined to show the change of the state of the element and the corresponding array of animation steps to show how the transition will take place.

We can include multiple trigger functions inside the animation property as comma-separated values.

To apply animation on the element, we need to include the trigger name in the element definition. the trigger name followed by @ symbol in the element tag. For example,

<div @fadeInOut></div>

This will apply the trigger fadeInOut to the <div> element.

Let us create the few animations to get a better understanding of the Angular animation concepts.

Fade In and Fade Out animation in Angular

We all use CRUD Operations in our Angular applications. So, we want to show an animation while adding or removing the element on the DOM. We will see how to animate the insertion and removal of the element to the list with a fade-in and fade-out effect.

Write the following code inside an app.component.ts file.

// app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  animations: [
    trigger('fadeInOut', [
      state('void', style({
        opacity: 0
      })),
      transition('void <=> *', animate(1000)),
    ]),
  ]
})
export class AppComponent implements OnInit {

  listItem = [];
  listOrder = 1;

  addElement(): void {
    const listitem = 'ListItem ' + this.listOrder;
    this.listOrder++;
    this.listItem.push(listitem);
  }
  removeElement(): void {
    this.listItem.length -= 1;
  }
  ngOnInit(): void {
  }
}

Here we have defined a trigger fadeInOut.

When the element is added in the DOM, it is the transition from void to wildcard (*) state. This is expressed using void =>; * syntax.

When an element is removed from the DOM, it is the transition from a wildcard (*) to the void state. This is expressed using * =>; void syntax.

When we use the same animation timing for both directions of the animation, we can use the shorthand syntax <;=>. As defined in the fadeInOut trigger, the animation from void =>; * and * => void will take 1000ms to complete.

Write the following code inside the app.component.html file.

<!-- app.component.html -->

<h3>Fade-In and Fade-Out animation</h3>
<div class="container">
  <div class = "row">
    <div class="col-md-4">
      <button class="btn btn-success" (click)="addElement()">Add Element</button>
    </div>
    <div class="col-md-4">
      <button class="btn btn-danger" (click)="removeElement()">Remove Element</button>
    </div>
  </div>
  <div class="row">
    <div style="width:200px; margin-left: 190px">
    <ul>
      <li *ngFor="let list of listItem" [@fadeInOut]>
        {{list}}
      </li>
    </ul>
  </div>
  </div>
</div>

In this code, we have used bootstrap classes to style the HTML elements.

Animation requires the trigger method so that it knows when to start. The trigger() method collects the states and transitions and gives the animation the name so that you can attach it to the triggering element in the HTML template.

The trigger() method describes the property name to watch for changes. When the change occurs, the trigger() method initiates the actions included in its definition. These actions can be transitions or other functions, as we’ll see later on.

Here, we have defined two buttons. Each button has click events. One button adds the ListItem by 1, and the other button removes the ListItem by 1.

We are displaying listItems using ul tag.

To add fadeInOut effect, we have written [@faceInOut] inside <li> tag.

See the output.

 

How to Use Angular 10 Animation

When you click on the Add Element button, it will add ListItem one by one with a fade-in and fade-out effect. Remove Element button removes the ListItem.

We are binding the fadeInOut trigger to the <li> element, which will show a fade-in and fade-out effect while being added and removed from the DOM.

When you’ve defined the animation trigger for a component, you can attach it to the element in that component’s template by wrapping the trigger name in brackets and preceding it with an @ symbol. Then, you can bind the trigger to a template expression using standard Angular property binding syntax. And that is what we have done in the above code.

Change Size Animation in Angular

We will create an animation to change the size of the <div> element, which is square on the button click.

To change the dimension of the element, we have to define two states,

  1. Initial State
  2. Final State

So, we will define two states inside the trigger() function.

Write the following code inside the app.component.ts file.

// app.component.ts

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  animations: [
    trigger('changeDivDimension', [
      state('initial', style({
        backgroundColor: 'purple',
        width: '100px',
        height: '100px'
      })),
      state('final', style({
        backgroundColor: 'blue',
        width: '200px',
        height: '200px'
      })),
      transition('initial=>final', animate('1500ms')),
      transition('final=>initial', animate('1000ms'))
    ]),
  ]
})

Here we have defined a trigger the changeDivDimension and two state functions inside the trigger. The element will be green in the “initial” state and will be red with increased width and height in the “final” state.

We have defined transitions for the state change. The transition from the “initial” state to “final” will take 1500ms, and from “final” state to “initial” will take 1000ms.

To change the state of our element, we will define the function in the class definition of our component. Include the following code in the AppComponent class.

currentState = 'initial';

changeState() {
  this.currentState = this.currentState === 'initial' ? 'final' : 'initial';
}

Here we have defined the changeState() method, which will switch the state of the element.

Open app.component.html file and add the following code:

<!-- app.component.html -->

<h3>Change Size animation</h3>
<div class="container">
  <div class = "row">
    <div class="col-md-4">
      <button (click)="changeState()" class="btn btn-primary">Change Size</button>
    </div>
    <div class="col-md-8">
      <div [@changeDivDimension]=currentState></div>
    </div>
  </div>
</div>

Output

 

Angular Animations

We have defined a button that will invoke the changeState function when clicked. We have defined an <div> element and applied the animation trigger changeDivDimension() to it.

When we click on the button, it flips the state of the <div> element, and its size will change with a transition effect.

Conclusion

In this article, we have learned about Angular 10 animations. We seen the concept of animation states and transitions. We also saw how to create a fade-in and fade-out effect in Angular and how to change the size of the HTML element using Angular animations.

That is it for this How to use Angular Animations Tutorial.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.