# 可复用动画
本主题提供了一些关于如何创建可复用动画的例子。
# 前提条件
在继续本主题前,你需要熟悉下列知识:
Angular 动画简介转场与触发器
# 创建可复用动画
要想创建可复用的动画,请使用 animation() 方法来在独立的 .ts文件中定义动画,并把该动画的定义声明为一个导出的 const变量。然后你就可以在应用的组件代码中通过 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 }}')
]);
在上面的代码片段中,通过把 transitionAnimation声明为一个导出的变量,就让它变成了可复用的。
注意:height、opacity、backgroundColor和 time这几个输入项会在运行期间被替换掉。
你还可以导出某个动画的一部分。比如,下列代码片段会导出 trigger这个动画。
src/app/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()函数来复用它。
src/app/open-close.component.ts
import { Component } from '@angular/core';
import { transition, trigger, useAnimation } 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']
})
# 关于 Angular 动画的更多知识
你可能还对下列内容感兴趣:
Angular 动画简介转场与触发器复杂动画序列路由转场动画