Angular animations enable developers to add motion and interactivity to their Angular applications. With Angular animations, developers can create smooth transitions, dynamic effects, and engaging user interfaces. This includes positions, sizes, transforms, colors, borders, and more. Angular animations allow developers to define animations using Angular directives and functions in components and templates.
Installation
Open Terminal and run the following command to install Angular animations.
ng add @angular/animations
Import BrowserAnimationsModule
into the Angular root application module.
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Example
The following Angular example demonstrates how to create a simple fade in/fade out animation using Angular animations. It toggles the visibility of an element with the click of a button, smoothly transitioning between the visible and hidden states. To use specific animation functions in component files, import them from @angular/animations
.
fadein-out.component.ts
import { animate, state, style, transition, trigger } from '@angular/animations';
import { Component } from '@angular/core';
@Component({
selector: 'app-fadein-out',
templateUrl: './fadein-out.component.html',
styleUrls: ['./fadein-out.component.scss'],
animations: [
// Define the fadeInOut animation trigger
trigger('fadeInOut', [
// Define the 'visible' state
state('visible', style({
opacity: 1
})),
// Define the 'hidden' state
state('hidden', style({
opacity: 0
})),
// Define the transition between 'visible' and 'hidden' states
transition('visible <=> hidden', [
// Animate the opacity over 500 milliseconds
animate(500)
])
])
]
})
export class FadeInOutComponent {
isVisible = true;
toggle() {
this.isVisible = !this.isVisible;
}
}
fadein-out.component.html
<h2>Fade in/Fade out demo</h2>
<!-- Button to toggle animation -->
<button (click)="toggle()">Toggle Animation</button>
<hr />
<!-- Div element to animate with fadeInOut animation trigger -->
<div [@fadeInOut]="isVisible ? 'visible' : 'hidden'">
Hello, Angular animations!
</div>
For more information, please visit https://angular.io/guide/animations.