How to create reusable animations in Angular
Creating reusable animations in Angular allows you to maintain consistent visual effects across components while reducing code duplication and improving maintainability. As the creator of CoreUI with extensive Angular experience since 2014, I’ve built comprehensive animation libraries for enterprise applications requiring consistent UI behavior. The most efficient approach uses animation factories and shared animation functions that can be imported and configured across multiple components. This pattern provides flexible, maintainable animations with customizable parameters and consistent timing throughout your application.
Create animation factories that can be imported and configured across multiple components for consistent effects.
import { trigger, state, style, transition, animate, AnimationTriggerMetadata } from '@angular/animations'
// Reusable fade animation factory
export function fadeAnimation(duration: string = '300ms'): AnimationTriggerMetadata {
return trigger('fade', [
state('in', style({ opacity: 1 })),
transition(':enter', [
style({ opacity: 0 }),
animate(duration)
]),
transition(':leave', [
animate(duration, style({ opacity: 0 }))
])
])
}
// Reusable slide animation factory
export function slideAnimation(direction: 'left' | 'right' | 'up' | 'down' = 'left', duration: string = '300ms'): AnimationTriggerMetadata {
const transforms = {
left: { enter: 'translateX(-100%)', leave: 'translateX(100%)' },
right: { enter: 'translateX(100%)', leave: 'translateX(-100%)' },
up: { enter: 'translateY(-100%)', leave: 'translateY(100%)' },
down: { enter: 'translateY(100%)', leave: 'translateY(-100%)' }
}
return trigger('slide', [
transition(':enter', [
style({ transform: transforms[direction].enter }),
animate(duration, style({ transform: 'translate(0)' }))
]),
transition(':leave', [
animate(duration, style({ transform: transforms[direction].leave }))
])
])
}
// Usage in components
@Component({
animations: [
fadeAnimation('400ms'),
slideAnimation('right', '250ms')
]
})
export class MyComponent { }
This code creates reusable animation factories that accept parameters for customization and return configured animation triggers. The factories use TypeScript for type safety and parameter validation, allowing components to import and configure animations with specific durations and directions. Each factory encapsulates the animation logic while providing a clean API for customization, ensuring consistent behavior across your application.
Best Practice Note:
This is the animation architecture pattern we use in CoreUI component libraries for consistent, maintainable UI effects. Consider creating a dedicated animations module to centralize all reusable animations and export them as a cohesive animation system.



