Simple Animations

Go back to Tutorial

You can build a simple animation that transitions an element between two states driven by a model attribute. Animations can be defined inside @Component metadata.

hero-list-basic.component.ts

import {

Component,

Input

} from ‘@angular/core’;

import {

trigger,

state,

style,

animate,

transition

} from ‘@angular/animations’;

With these, you can define an animation trigger called heroState in the component metadata. It uses animations to transition between two states: active and inactive. When a hero is active, the element appears in a slightly larger size and lighter color.

hero-list-basic.component.ts (@Component excerpt)

animations: [

trigger(‘heroState’, [

state(‘inactive’, style({

backgroundColor: ‘#eee’,

transform: ‘scale(1)’

})),

state(‘active’,   style({

backgroundColor: ‘#cfd8dc’,

transform: ‘scale(1.1)’

})),

transition(‘inactive => active’, animate(‘100ms ease-in’)),

transition(‘active => inactive’, animate(‘100ms ease-out’))

])

]

 

In this example, you are defining animation styles (color and transform) inline in the animation metadata. Now, using the [@triggerName] syntax, attach the animation that you just defined to one or more elements in the component’s template.

hero-list-basic.component.ts (excerpt)

template: `

<ul>

<li *ngFor=”let hero of heroes”

[@heroState]=”hero.state”

(click)=”hero.toggleState()”>

{{hero.name}}

</li>

</ul>

`,

 

Here, the animation trigger applies to every element repeated by an ngFor. Each of the repeated elements animates independently. The value of the attribute is bound to the expression hero.state and is always either active or inactive.

With this setup, an animated transition appears whenever a hero object changes state. Here’s the full component implementation:

hero-list-basic.component.ts

import {

Component,

Input

} from ‘@angular/core’;

import {

trigger,

state,

style,

animate,

transition

} from ‘@angular/animations’;

import { Hero } from ‘./hero.service’;

@Component({

selector: ‘hero-list-basic’,

template: `

<ul>

<li *ngFor=”let hero of heroes”

[@heroState]=”hero.state”

(click)=”hero.toggleState()”>

{{hero.name}}

</li>

</ul>

`,

styleUrls: [‘./hero-list.component.css’],

animations: [

trigger(‘heroState’, [

state(‘inactive’, style({

backgroundColor: ‘#eee’,

transform: ‘scale(1)’

})),

state(‘active’,   style({

backgroundColor: ‘#cfd8dc’,

transform: ‘scale(1.1)’

})),

transition(‘inactive => active’, animate(‘100ms ease-in’)),

transition(‘active => inactive’, animate(‘100ms ease-out’))

])

]

})

export class HeroListBasicComponent {

@Input() heroes: Hero[];

}

 

Go back to Tutorial

Share this post
[social_warfare]
Animation Setup
Keyframe Animations

Get industry recognized certification – Contact us

keyboard_arrow_up