Extended Ecosystem
Legacy Animations

Animaciones reutilizables

IMPORTANTE: El paquete @angular/animations ahora está deprecado. El equipo de Angular recomienda usar CSS nativo con animate.enter y animate.leave para animaciones en todo código nuevo. Aprende más en la nueva guía de animaciones de entrada y salida. También consulta Migrando del paquete de Animations de Angular para aprender cómo puedes comenzar a migrar a animaciones CSS puras en tus aplicaciones.

Este tema proporciona algunos ejemplos de cómo crear animaciones reutilizables.

Crear animaciones reutilizables

Para crear una animación reutilizable, usa la función animation() para definir una animación en un archivo .ts separado y declara esta definición de animación como una variable de exportación const. Luego puedes importar y reutilizar esta animación en cualquiera de los componentes de tu aplicación usando la función useAnimation().

src/app/animations.ts

import {animation, style, animate, trigger, transition, useAnimation} from '@angular/animations';export const transitionAnimation = animation([  style({    height: '{{ height }}',    opacity: '{{ opacity }}',    backgroundColor: '{{ backgroundColor }}',  }),  animate('{{ time }}'),]);export const sharedAnimation = animation([  style({    height: 0,    opacity: 1,    backgroundColor: 'red',  }),  animate('1s'),]);export const triggerAnimation = trigger('openClose', [  transition('open => closed', [    useAnimation(transitionAnimation, {      params: {        height: 0,        opacity: 1,        backgroundColor: 'red',        time: '1s',      },    }),  ]),]);

En el fragmento de código anterior, transitionAnimation se hace reutilizable declarándola como una variable de exportación.

ÚTIL: Las entradas height, opacity, backgroundColor y time se reemplazan durante el tiempo de ejecución.

También puedes exportar una parte de una animación. Por ejemplo, el siguiente fragmento exporta el trigger de animación.

src/app/animations.1.ts

import {animation, style, animate, trigger, transition, useAnimation} from '@angular/animations';export const transitionAnimation = animation([  style({    height: '{{ height }}',    opacity: '{{ opacity }}',    backgroundColor: '{{ backgroundColor }}',  }),  animate('{{ time }}'),]);export const sharedAnimation = animation([  style({    height: 0,    opacity: 1,    backgroundColor: 'red',  }),  animate('1s'),]);export const triggerAnimation = trigger('openClose', [  transition('open => closed', [    useAnimation(transitionAnimation, {      params: {        height: 0,        opacity: 1,        backgroundColor: 'red',        time: '1s',      },    }),  ]),]);

Desde este punto, puedes importar variables de animación reutilizables en la clase de tu componente. Por ejemplo, el siguiente fragmento de código importa la variable transitionAnimation y la usa a través de la función useAnimation().

src/app/open-close.component.ts

import {Component, input} from '@angular/core';import {transition, trigger, useAnimation, AnimationEvent} from '@angular/animations';import {transitionAnimation} from './animations';@Component({  selector: 'app-open-close-reusable',  animations: [    trigger('openClose', [      transition('open => closed', [        useAnimation(transitionAnimation, {          params: {            height: 0,            opacity: 1,            backgroundColor: 'red',            time: '1s',          },        }),      ]),    ]),  ],  templateUrl: 'open-close.component.html',  styleUrls: ['open-close.component.css'],})export class OpenCloseBooleanComponent {  isOpen = false;  toggle() {    this.isOpen = !this.isOpen;  }  logging = input(false);  onAnimationEvent(event: AnimationEvent) {    if (!this.logging) {      return;    }  }}

Más sobre animaciones de Angular

También puede que te interese lo siguiente: