可複用動畫
Reusable animations
前提條件
Prerequisites
對下列概念有基本的理解:
A basic understanding of the following concepts:
Angular 動畫函式庫中的 AnimationOptions 介面讓你能建立可以在不同元件之間複用的動畫。
The AnimationOptions interface in Angular animations enables you to create animations that you can reuse across different components.
建立可複用動畫
Creating reusable animations
要想建立可複用的動畫,請使用 animation()
方法來在獨立的 .ts
檔案中定義動畫,並把該動畫的定義宣告為一個匯出的 const
變數。然後你就可以在應用的元件程式碼中透過 useAnimation()
來匯入並複用它了。
To create a reusable animation, use the animation()
method to define an animation in a separate .ts
file and declare this animation definition as a const
export variable. You can then import and reuse this animation in any of your application components using the useAnimation()
API.
import {
animation, trigger, animateChild, group,
transition, animate, style, query
} from '@angular/animations';
export const transAnimation = animation([
style({
height: '{{ height }}',
opacity: '{{ opacity }}',
backgroundColor: '{{ backgroundColor }}'
}),
animate('{{ time }}')
]);
在上面的程式碼片段中,透過把 transAnimation
宣告為一個匯出的變數,就讓它變成了可複用的。
In the above code snippet, transAnimation
is made reusable by declaring it as an export variable.
注意:height
、opacity
、backgroundColor
和 time
這幾個輸入項會在執行期間被替換掉。
Note: The height
, opacity
, backgroundColor
, and time
inputs are replaced during runtime.
你可以在元件類別中匯入這個可複用的 transAnimation
變數,並透過 useAnimation()
方法來複用它。程式碼如下:
You can import the reusable transAnimation
variable in your component class and reuse it using the useAnimation()
method as shown below.
import { Component } from '@angular/core';
import { transition, trigger, useAnimation } from '@angular/animations';
import { transAnimation } from './animations';
@Component({
selector: 'app-open-close-reusable',
animations: [
trigger('openClose', [
transition('open => closed', [
useAnimation(transAnimation, {
params: {
height: 0,
opacity: 1,
backgroundColor: 'red',
time: '1s'
}
})
])
])
],
templateUrl: 'open-close.component.html',
styleUrls: ['open-close.component.css']
})
關於 Angular 動畫的更多知識
More on Angular animations
你可能還對下列內容感興趣:
You may also be interested in the following: