拡張エコシステム
レガシーアニメーション

再利用可能なアニメーション

IMPORTANT: @angular/animationsパッケージは現在非推奨です。Angularチームは、新しく書くコードのアニメーションにはanimate.enteranimate.leaveを使ったネイティブCSSの利用を推奨します。詳しくは、新しいenterとleaveのアニメーションガイドを参照してください。また、アプリケーションで純粋なCSSアニメーションへの移行を始める方法については、AngularのAnimationsパッケージからの移行も参照してください。

このトピックでは、再利用可能なアニメーションを作成する方法の例をいくつか紹介します。

再利用可能なアニメーションを作成する

再利用可能なアニメーションを作成するには、animation()関数を使って別の.tsファイルにアニメーションを定義し、そのアニメーション定義を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をエクスポート変数として宣言することで再利用可能にしています。

HELPFUL: heightopacitybackgroundColortimeの入力値は実行時に置き換えられます。

アニメーションの一部もエクスポートできます。 たとえば、次のスニペットではアニメーションのtriggerをエクスポートしています。

animations.1.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アニメーションについてさらに詳しく

以下の項目にも興味があるかもしれません: