本主题提供了一些关于如何创建可复用动画的例子。
在继续本主题前,你需要熟悉下列知识:
要想创建可复用的动画,请使用 animation() 方法来在独立的 .ts 文件中定义动画,并把该动画的定义声明为一个导出的 const 变量。然后你就可以在应用的组件代码中通过 useAnimation() 来导入并复用它了。
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 这个动画。
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() 函数来复用它。
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']
})