Image for post
Image for post

Angular 6 Animations From Scratch

This post has been published first on CodingTheSmartWay.com.

Subscribe On YouTube | Live Demo | Code on GitHub

In this tutorial you’ll learn how to make use of the Angular Animations Module in your Angular 6 application. Angular offers the ability to create compelling animations and activate them based on a variety of factors. You can place animations on any HTML element and make them occur based on defined events.

Including engaging graphical transitions in the user interface of your application is enhancing the user experience and at the same time it is making sure that the application is easier to use. E.g. a certain animation can help to draw the user’s attention to a special UI elements.

In this tutorial you’ll learn how to implement animations by following a practical sample application. Let’s take a quick look at what we will be building.

What We’re Going To Build

The sample application we’re going to build will look like the following:

Image for post
Image for post

The initial screen shows a big green rectangle in the middle of the screen. In addition you have access to two buttons: Change To State 2 and Change To State 1. By using those two buttons you’re able to trigger animations of the rectangle. E.g. if you click on button Change To State 2 the rectangle will show an animation and change to the following appearance:

Image for post
Image for post

Afterwards clicking on button Change To State 1 triggers another animation which transforms the rectangle back to the initial appearance.

Let’s build this application from scratch …

If you like CodingTheSmartWay, then consider supporting us via Patreon. With your help we’re able to release developer tutorial more often. Thanks a lot! Become A Patron!

Setting Up The Angular 6 Project

To get started with a practical Angular 6 Animations project, we’ll need to set up an Angular project first. Therefore we’ll be using Angular CLI:

$ ng new angularanimation

This commend is creating a new project directory angularanimation and installing the Angular 6 default project inside that newly created folder. Now let’s change into that folder:

$ cd angularanimation

and test if everything is working correctly by starting up the development web server:

$ ng serve

If you now access URL http://localhost:4200/ in the browser you should be able to see the following output:

Image for post
Image for post

Setting Up Angular Animations

Now that the Angular 6 project is ready we’re able to set up Angular Animations for this project. The first step is to add the following import statement in app.module.ts:

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

Next we need to add BrowserAnimationsModule to the array which is assigned to the import property of the @NgModule decorator:

imports: [
BrowserModule,
BrowserAnimationsModule
],

This is making the content of BrowserAnimationsModule available to our application, so that we’re able to import animations in our components.

Let’s create a new component first:

$ ng g c animate

This is creating the following four new files in your project:

  • animate.component.ts
  • animate.component.spec.ts
  • animate.component.html
  • animate.component.css

The new component AnimateComponent is automatically added to the main application module in app.module.ts and therewith it is made available in your application:

import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { AnimateComponent } from './animate/animate.component';
@NgModule({
declarations: [
AppComponent,
AnimateComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

Manage State Changes in AppComponent

The application should trigger animations based on state changes which are invoked by pressing buttons. To manage the state of the application we need to introduce a class member variable in AppComponent:

import { Component } from '@angular/core';@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'angularanimation01';
toState = 'state1'; changeState(state: any) {
this.toState = state;
}
}

The member variable is named toState and is changed by the method changeState. This method is used as an event handler method for the click event of the buttons. Let’s take a look at the corresponding HTML template code which needs to be inserted into app.component.html:

<div class="container p-4">
<div class="row">
<div class="col text-center">
<a (click)="changeState('state2')" class="btn btn-danger">Change To State 2</a>
</div>
<div class="col text-center">
<a (click)="changeState('state1')" class="btn btn-info">Change To State 1</a>
</div>
</div>
<div class="row justify-content-center align-items-center">
<app-animate [currentState]="toState"></app-animate>
</div>
</div>

We’re making use of Bootstrap 4 CSS classes in this template code. This requires us to include the Bootstrap CSS file in our application. The easierst way to do so, is to include Bootstrap from CDN in index.html by adding the following line of code to the head section:

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

The template code attached the changeState method to the click event of the two buttons. In the first case the value which is set by changeState is state2 and in the second case the value is state1.

Furthermore the output of AnimateComponent is included by using the element <app-animate>. An input property with name currentState will be available, so that we’re able to bind this property to the value of the toState member variable.

Implementing AnimateComponent

Having prepared AppComponent we can now continue with the implementation of AnimateComponent. First, we need to include a div element in animate.component.html which is displaying the rectangle which is being animated.

<div [@changeState]="currentState" class="myblock mx-auto"></div>

The corresponding CSS code for the myblock class needs to be inserted into animate.component.css:

.myblock {
background-color: green;
width: 300px;
height: 250px;
border-radius: 5px;
margin: 5rem;
}

Finally we’re able to define the animations / transitions in file animate.component.ts:

import { Component, OnInit, Input } from '@angular/core';
import { trigger, state, style, animate, transition } from '@angular/animations';
@Component({
selector: 'app-animate',
templateUrl: './animate.component.html',
styleUrls: ['./animate.component.css'],
animations: [
trigger('changeState', [
state('state1', style({
backgroundColor: 'green',
transform: 'scale(1)'
})),
state('state2', style({
backgroundColor: 'red',
transform: 'scale(1.5)'
})),
transition('*=>state1', animate('300ms')),
transition('*=>state2', animate('2000ms'))
])
]
})
export class AnimateComponent implements OnInit {
@Input() currentState; constructor() { } ngOnInit() {
}
}

Note, that we’re first importing trigger, state, style, animate, and transition from the @angular/animations package. Having imported those assets gives us the possibility of defining the animations we’d like to include in that components.

To define animations the animations property of the @Component decorator is used. By using the function trigger inside the array which is assigned to that property we’re defining animations which are used if the changeState trigger is activated (each time the currentState value changes). Therefore the string value changeState is passed into the call of that function.

The second parameter is an array again which is consisting of four element. For the first two items the state function is called and the style is defined which is used for state1 and state2. For each state we’re setting a different background color and a different scale.

As the last two elements we’re defining transitions (by using the transition function). The first transition is defined by the string *=>state1. This simply means that this transition is invoked each time state1 is set regardless of the previous state. By using the animate function and passing in the string value 300ms we’re defining that the transition has a duration of 300 milliseconds.

In a similar way the second transition is defined. This way we’re defining the transition which is taking place if state2 is entered.

Conclusion

Angular Animations are a powerful way to implement sophisticated and compelling animations for your Angular single page web application. Having followed this tutorial you have now a profound understanding of how to setup and apply Angular Animations in your Angular 6 project.

This post has been published first on CodingTheSmartWay.com.

#1 Angular 6 — The Complete Guide

Master Angular (Angular 2+, incl. Angular 6) and build awesome, reactive web apps with the successor of Angular.js
Go To Course …

Disclaimer: This post contains affiliate links, which means that if you click on one of the product links, I’ll receive a small commission. This helps support this blog!

CodingTheSmartWay.com Blog

CodingTheSmartWay.com

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store