Home / Angular / Angular 5 Animation Tutorial

Angular 5 Animation Tutorial

Installing the Animation Library
Until recently, the Angular Animation library was installed by default. But now, we have to add it manually.

Visit the console in the project folder and type:

$ npm install @angular/animations@latest –save
Next, in /src/app/app.module.ts we need to import it:

// Other imports removed for brevity
import { BrowserAnimationsModule } from ‘@angular/platform-browser/animations’;

@NgModule({
  ...
  imports: [
    // other modules removed for brevity
    BrowserAnimationsModule
  ],
})

Importing Animations
We want to add animations to our home component. So, in the /src/app/home/home.component.ts file, import at the top:

import { trigger,style,transition,animate,keyframes,query,stagger } from ‘@angular/animations’;
Defining Animations
Animations are defined within the @Component decorator like so:

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss'],
  animations: [

    // Animations here...

  ]
})

The first animation-specific function that we use is trigger(). This allows us to define the name of the animation in the first parameter, and then an array of other animation-specific functions in the next.

  animations: [

    trigger('goals', [

    ])
  ]

We’ve made a new animation called goals here. Next, we use transition() to define a transition between two different states. States can be defined explicitely through the state function, or we can use a wildcard * as a state.

There are a variety of transition states, but the one we’re going to use is * => *:

  animations: [

    trigger('goals', [
      transition('* => *', [
      ])
    ])

  ]

This means, for the animation trigger goals, if there is any transition taking place, execute the following..

Next, we’re going to use the query function to target DOM elements that are only entering the DOM:

  animations: [

    trigger('goals', [
      transition('* => *', [

        query(':enter', style({ opacity: 0 }), {optional: true}),

        query(':enter', stagger('300ms', [
          animate('.6s ease-in', keyframes([
            style({opacity: 0, transform: 'translateY(-75%)', offset: 0}),
            style({opacity: .5, transform: 'translateY(35px)',  offset: 0.3}),
            style({opacity: 1, transform: 'translateY(0)',     offset: 1.0}),
          ]))]), {optional: true})
      ])
    ])
  ]

Wow, that’s a lot! Well, first, we’re setting any DOM element that is bound to the goals animation, to an opacity of 0 when it enters.

Next, we’re creating a stagger animation with a delay of 300ms between each element.

After that, we’re animating the elements with a .6s ease-in animation and using keyframes to allow us to create a multi-step animation for each item.

Is all of this necessary? No, you could get rid of the stagger and the keyframes, but this more complex approach will show you the full power of Angular 5 Animations.

Applying the Animation to the Template
Before we add to the template, let’s give our default goals[] array some initial values:

goals = [‘My first life goal’, ‘I want to climb a mountain’, ‘Go ice skiing’];
Now that we have our animations defined in the component, let’s make the following adjustments in the app.component.html template:

Great! Save it and reload the browser.

You should see each of the 3 goal items animated in a unique stagger. Try adding a goal yourself with the form, and you will see it too animates in as expected.

How about animating a list item when it’s removed from the DOM?

In the template, add a click event here:

<!-- From: -->
<p class="life-container" *ngFor="let goal of goals" (click)="removeItem(i)">

<!-- To: -->
<p class="life-container" *ngFor="let goal of goals; let i = index" (click)="removeItem(i)">
In the component class, add the removeItem() method:

  removeItem(i) {
    this.goals.splice(i, 1);
  }

Then, in the animations above, add the following:

  animations: [

    trigger('goals', [
      transition('* => *', [

        query(':enter', style({ opacity: 0 }), {optional: true}),

        query(':enter', stagger('300ms', [
          animate('.6s ease-in', keyframes([
            style({opacity: 0, transform: 'translateY(-75%)', offset: 0}),
            style({opacity: .5, transform: 'translateY(35px)',  offset: 0.3}),
            style({opacity: 1, transform: 'translateY(0)',     offset: 1.0}),
          ]))]), {optional: true})
          ,
        query(':leave', stagger('300ms', [
          animate('.6s ease-out', keyframes([
            style({opacity: 1, transform: 'translateY(0)', offset: 0}),
            style({opacity: .5, transform: 'translateY(35px)',  offset: 0.3}),
            style({opacity: 0, transform: 'translateY(-75%)',     offset: 1.0}),
          ]))]), {optional: true})
      ])
    ])
  ]

Notice we’ve added a query for: leave? It’s as simple as that and then reversing some of the style values to produce the opposite effect of opacity and Y movements.

Save it, and try clicking on any of the goal items in the list. They will animate out!

About Mohammad Fareed

Software Engineer @ Tekzenit.

Check Also

What’s new In Angular 5? What Is the Difference Between Angular 4 and Angular 5?

Angular, one of the best open-source JavaScript frameworks for web application development, recently upgraded with …

Leave a Reply

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