Angular 생태계
애니메이션(이전 방식)

재사용 가능한 애니메이션

중요: @angular/animations 패키지는 이제 사용 중단 권고(deprecated) 상태입니다. Angular 팀은 새로 작성하는 모든 코드에서 animate.enter와 animate.leave를 사용하는 네이티브 CSS 애니메이션을 권장합니다. 새로운 진입 및 퇴장 애니메이션 가이드에서 자세히 알아보세요. Angular 애니메이션 패키지에서 마이그레이션하기를 참고하면 애플리케이션을 순수 CSS 애니메이션으로 전환하는 방법도 확인할 수 있습니다.

이 문서에서는 재사용 가능한 애니메이션을 만드는 예제를 살펴봅니다.

재사용 가능한 애니메이션 만들기

재사용 가능한 애니메이션을 만들려면 별도의 .ts 파일에서 animation() 함수로 애니메이션을 정의하고, 이 정의를 const 변수로 선언해서 내보내면 됩니다. 그러면 애플리케이션 컴포넌트에서 이 애니메이션을 가져와 useAnimation() 함수로 재사용할 수 있습니다.

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 }}'),
]);

위 코드에서는 transitionAnimation을 내보내는 변수로 선언해서 재사용할 수 있도록 만들었습니다.

도움말: height, opacity, backgroundColor, time 입력 값은 런타임에 대체됩니다.

애니메이션의 일부만 내보낼 수도 있습니다. 예를 들어 다음 코드에서는 애니메이션 trigger를 내보냅니다.

animations.ts

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

이제 컴포넌트 클래스에서 재사용 가능한 애니메이션 변수를 가져올 수 있습니다. 예를 들어 다음 코드에서는 transitionAnimation 변수를 가져와 useAnimation() 함수로 사용합니다.

open-close.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.html',
  styleUrls: ['open-close.css'],
})

Angular 애니메이션 더 알아보기

다음 문서도 참고해 보세요: