angular 動畫
介紹 (Introduction)
Animation is defined as the transition from an initial state to a final state. It is an integral part of any modern web application. Animation not only helps us create a great UI but it also makes the application interesting and fun to use. A well-structured animation keeps the user engaged with the application and enhances the user experience.
動畫定義為從初始狀態到最終狀態的過渡。 它是任何現代Web應用程序不可或缺的一部分。 動畫不僅可以幫助我們創建出色的UI,還可以使應用程序變得有趣且易于使用。 結構良好的動畫使用戶保持與應用程序的互動,并增強了用戶體驗。
Angular allows us to create animations which provides us similar native performance as CSS animations. In this article, we will learn how we can create animation using Angular 6.
Angular允許我們創建動畫,從而為我們提供與CSS動畫類似的本機性能。 在本文中,我們將學習如何使用Angular 6創建動畫。
We will use Visual Studio Code for our demo.
我們將使用Visual Studio Code進行演示。
先決條件 (Prerequisites)
Install VS code and Angular CLI.
安裝VS代碼和Angular CLI。
If you are new to Angular, then refer to my previous article Getting Started With Angular 6.0 to set up the Angular 6 development environment on your machine.
如果您不熟悉Angular,請參考我以前的文章Angular 6.0入門,在您的機器上設置Angular 6開發環境。
源代碼 (Source Code)
Download the source code from GitHub.
從GitHub下載源代碼。
了解角度動畫狀態 (Understanding Angular Animation States)
Animation involves transition from one state of an element to another state. Angular defines three different states for an element:
動畫涉及從元素的一種狀態過渡到另一種狀態。 Angular為一個元素定義了三種不同的狀態:
Void state — represents the state of an element which is not part of the DOM. This state occurs when an element is created but not yet placed in the DOM or the element is removed from the DOM. This state is useful when we want to create animation while adding or removing an element from our DOM. To define this state in our code we use the keyword
void
.無效狀態-表示不屬于DOM的元素的狀態。 當創建元素但尚未將其放置在DOM中或從DOM中刪除該元素時,會發生此狀態。 當我們要在從DOM中添加或刪除元素時創建動畫時,此狀態很有用。 要在我們的代碼中定義此狀態,我們使用關鍵字
void
。The wildcard state — This is also known as the default state of the element. The styles defined for this state are applicable to the element regardless of its current animation state. To define this state in our code we use the
*
symbol.通配符狀態-這也稱為元素的默認狀態。 為此元素定義的樣式適用于該元素,而不管其當前的動畫狀態如何。 要在我們的代碼中定義此狀態,我們使用
*
符號。- Custom state — This is the custom state of the element and it needs to be defined explicitly in the code. To define this state in our code, we can use any custom name of our choice. 自定義狀態-這是元素的自定義狀態,需要在代碼中明確定義。 要在我們的代碼中定義此狀態,我們可以使用我們選擇的任何自定義名稱。
動畫過渡時間 (Animation Transition Timing)
To show the animation transition from one state to another, we define animation transition timing in our application.
為了顯示動畫從一種狀態過渡到另一種狀態,我們在應用程序中定義了動畫過渡時間。
Angular provides the following three timing properties:
Angular提供以下三個計時屬性:
持續時間 (Duration)
This property represents the time our animation takes to complete from start (initial state) to finish (final state). We can define the duration of animation in the following three ways:
此屬性表示動畫從開始(初始狀態)到完成(最終狀態)所花費的時間。 我們可以通過以下三種方式定義動畫的持續時間:
- Using an integer value to represent the time in milliseconds. E.g.- 500 使用整數值表示時間(以毫秒為單位)。 例如500
- Using a string value to represent the time in milliseconds. E.g. — ‘500ms’ 使用字符串值表示時間(以毫秒為單位)。 例如-“ 500ms”
- Using a string value to represent the time in seconds. E.g. — ‘0.5s’ 使用字符串值表示時間(以秒為單位)。 例如-'0.5s'
延遲 (Delay)
This property represents the duration between the animation trigger and the beginning of the actual transition. This property also follows the same syntax as duration. To define the delay, we need to add the delay value after the duration value in a string format — ‘ Duration Delay’. Delay is an optional property.
此屬性表示動畫觸發器與實際過渡開始之間的持續時間。 此屬性還遵循與duration相同的語法。 要定義延遲,我們需要在持續時間值之后以字符串格式-“ Duration Delay”添加延遲值。 延遲是可選屬性。
For example:
例如:
- ‘0.3s 500ms’. This means the transition will wait for 500ms and then run for 0.3s. '0.3s 500ms'。 這意味著過渡將等待500ms,然后運行0.3s。
緩和 (Easing)
This property represents how the animation accelerates or decelerates during its execution. We can define the easing by adding it as the third variable in the string after duration and delay. If the delay value is not present, then easing will be the second value. This is also an optional property.
此屬性表示動畫在執行過程中如何加速或減速。 我們可以通過在持續時間和延遲之后將其添加為字符串中的第三個變量來定義寬松。 如果延遲值不存在,則緩動將是第二個值。 這也是一個可選屬性。
For example:
例如:
- ‘0.3s 500ms ease-in’ — This means the transition will wait for 500ms and then run for 0.3s (300ms) with ease-in effect. “ 0.3s 500ms緩入” —這意味著過渡將等待500ms,然后以緩入效果運行0.3s(300ms)。
- ‘300ms ease-out’. — This means the transition will run for 300ms (0.3s) with ease-out effect. “ 300ms緩解”。 —這意味著過渡將持續300ms(0.3s),具有緩和效果。
創建Angular 6應用程序 (Creating the Angular 6 application)
Open command prompt in your machine and execute the following set of commands:
在計算機中打開命令提示符,然后執行以下命令集:
- mkdir ngAnimationDemo mkdir ngAnimationDemo
- cd ngAnimationDemo cd ngAnimationDemo
- ng new ngAnimation ng new ngAnimation
These commands will create a directory with the name ngAnimationDemo
and then create an Angular application with the name ngAnimation
inside that directory.
這些命令將創建一個名稱的目錄ngAnimationDemo
,然后創建一個名為的角度應用ngAnimation
該目錄內。
Open the ngAnimation app using VS code. Now we will create our component.
使用VS代碼打開ngAnimation應用。 現在,我們將創建我們的組件。
Navigate to View >> Integrated Te
rminal. This will open a terminal window in VS Code.
導航至View >> Integrated Te
終端。 這將在VS Code中打開一個終端窗口。
Execute the following command to create the component.
執行以下命令以創建組件。
ng g c animationdemo
This will create our component animationdemo
inside the /src/app
folder.
這將在/src/app
文件夾中創建我們的組件animationdemo
。
To use Angular animation we need to import BrowserAnimationsModule
which is an animation-specific module in our application. Open the app.module.ts file and include the import definition as shown below:
要使用Angular動畫,我們需要導入BrowserAnimationsModule
,這是我們應用程序中特定于動畫的模塊。 打開app.module.ts文件,并包含導入定義,如下所示:
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
// other import definitions@NgModule({ imports: [BrowserAnimationsModule // other imports]})
了解角度動畫語法 (Understanding the Angular Animation Syntax)
We will write our animation code inside the component’s metadata. The syntax for the animation is shown below:
我們將在組件的元數據中編寫動畫代碼。 動畫的語法如下所示:
@Component({
// other component properties.animations: [trigger('triggerName'), [state('stateName', style())transition('stateChangeExpression', [Animation Steps])]]
})
Here we will use a property called animations
. This property will take an array as input. The array contains one or more “trigger”. Each trigger has a unique name and an implementation. The state and transitions for our animation need to be defined in the trigger implementation.
在這里,我們將使用一個名為animations
的屬性。 該屬性將數組作為輸入。 該數組包含一個或多個“觸發器”。 每個觸發器都有一個唯一的名稱和一個實現。 動畫的狀態和過渡需要在觸發器實現中定義。
Each state function has a “stateName” defined to uniquely identify the state and a style function to show the style of the element in that state.
每個狀態函數都有一個定義為唯一標識狀態的“ stateName”和一個樣式函數,用于顯示該狀態下元素的樣式。
Each transition function has a stateChangeExpression
defined to show the change of the state of an element and the corresponding array of animation steps to show how the transition will take place. We can include multiple trigger functions inside the animation property as comma separated values.
每個過渡函數都有一個stateChangeExpression
定義,以顯示元素狀態的變化以及相應的動畫步驟數組,以顯示過渡如何發生。 我們可以在animation屬性內包含多個觸發函數,以逗號分隔的值。
These functions trigger, and state and transition are defined in the @angular/animations
module. Hence, we need to import this module in our component.
這些函數觸發,狀態和轉換在@angular/animations
模塊中定義。 因此,我們需要將此模塊導入組件中。
To apply animation on an element, we need to include the trigger name in the element definition. Include the trigger name followed by @
symbol in the element tag. Refer to the sample code below:
要將動畫應用于元素,我們需要在元素定義中包括觸發器名稱。 在元素標簽中包含觸發器名稱,后跟@
符號。 請參考下面的示例代碼:
<div @changeSize></div>
This will apply the trigger changeSize
to the <d
iv> element.
這會將觸發器changeSize
應用于<d
iv>元素。
Let us create a few animations to get a better understanding of the Angular animation concepts.
讓我們創建一些動畫,以更好地了解Angular動畫概念。
更改大小動畫 (Change Size Animation)
We will create an animation to change the size of a <d
iv> element on a button click.
我們將創建一個動畫來更改按鈕單擊時<d
iv>元素的大小。
Open the animationdemo.component.ts
file and add the following import definition:
打開animationdemo.component.ts
文件并添加以下導入定義:
import { trigger, state, style, animate, transition } from '@angular/animations';
Add the following animation property definition in the component metadata:
在組件元數據中添加以下動畫屬性定義:
animations: [trigger('changeDivSize', [state('initial', style({backgroundColor: 'green',width: '100px',height: '100px'})),state('final', style({backgroundColor: 'red',width: '200px',height: '200px'})),transition('initial=>final', animate('1500ms')),transition('final=>initial', animate('1000ms'))]),
]
Here we have defined a trigger changeDivSize
and two state functions inside the trigger. The element will be green in the “initial” state and will be red with an increased width and height in the “final” state.
在這里,我們在觸發器內部定義了一個觸發器changeDivSize
和兩個狀態函數。 元素在“初始”狀態下將為綠色,而在“最終”狀態下將以增加的寬度和高度為紅色。
We have defined transitions for the state change. Transition from “initial” state to “final” will take 1500ms and from “final” state to “initial” will take 1000ms.
我們為狀態更改定義了過渡。 從“初始”狀態到“最終”的轉換將花費1500ms,從“最終”狀態到“初始”的轉換將花費1000ms。
To change the state of our element we will define a function in the class definition of our component. Include the following code in the AnimationdemoComponent
class:
要更改元素的狀態,我們將在組件的類定義中定義一個函數。 在AnimationdemoComponent
類中包含以下代碼:
currentState = 'initial';changeState() {this.currentState = this.currentState === 'initial' ? 'final' : 'initial';
}
Here we have defined a changeState
method which will switch the state of the element.
在這里,我們定義了一個changeState
方法,該方法將切換元素的狀態。
Open animationdemo.component.html
file and add the following code:
打開animationdemo.component.html
文件并添加以下代碼:
<h3>Change the div size</h3>
<button (click)="changeState()">Change Size</button>
<br />
<div [@changeDivSize]=currentState></div>
<br />
We have defined a button which will invoke the changeState
function when clicked. We have defined a <d
iv> element and applied the animation trigger changeD
ivSize to it. When we click on the button it will flip the state of the
<div> element and its size will change with a transition effect.
我們定義了一個按鈕,單擊該按鈕將調用changeState
函數。 我們定義了一個<d
iv>元素,并將動畫igger changeD
ivSize應用于該元素。 當我們按一下按鈕,將翻轉狀態ò f the
<div>元素和它的尺寸將與過渡效果而改變。
Before executing the application, we need to include the reference to our Animationdemo
component inside the app.component.html
file.
在執行應用程序之前,我們需要在app.component.html
文件中包括對Animationdemo
組件的app.component.html
。
Open app.component.html
file. You can see we have some default HTML code in this file. Delete all the code and put the selector of our component as shown below:
打開app.component.html
文件。 您可以看到我們在此文件中有一些默認HTML代碼。 刪除所有代碼,然后將組件的選擇器放入如下圖所示:
<app-animationdemo></app-animationdemo>
To execute the code run the ng serve
command in the VS code terminal window. After running this command, it will ask to open http://localhost:4200
in the browser. So, open any browser on your machine and navigate to this URL. You can see a webpage as shown below. Click on the button to see the animation.
要執行代碼,請在VS代碼終端窗口中運行ng serve
命令。 運行此命令后,它將要求在瀏覽器中打開http://localhost:4200
。 因此,打開計算機上的所有瀏覽器并導航到該URL。 您可以看到如下所示的網頁。 單擊按鈕以查看動畫。
氣球效果動畫 (Balloon effect animation)
In the previous animation, the transition happened in two directions. In this section, we will learn how to change the size from all directions. It will be similar to inflating and deflating a balloon, hence the name balloon effect animation.
在上一個動畫中,過渡發生在兩個方向。 在本節中,我們將學習如何從各個方向更改大小。 它類似于為氣球充氣和放氣,因此命名為氣球效果動畫。
Add the following trigger definition in the animation property:
在animation屬性中添加以下觸發器定義:
trigger('balloonEffect', [state('initial', style({backgroundColor: 'green',transform: 'scale(1)'})),state('final', style({backgroundColor: 'red',transform: 'scale(1.5)'})),transition('final=>initial', animate('1000ms')),transition('initial=>final', animate('1500ms'))]),
Here, instead of defining the width and height property, we are using the transform property to change the size from all directions. The transition will occur when the state of the element is changed.
在這里,我們沒有使用width屬性來定義width和height屬性,而是使用transform屬性來從各個方向更改大小。 當元素的狀態更改時,將發生過渡。
Add the following HTML code in the app.component.html
file:
在app.component.html
文件中添加以下HTML代碼:
<h3>Balloon Effect</h3>
<div (click)="changeState()" style="width:100px;height:100px; border-radius: 100%; margin: 3rem; background-color: green"[@balloonEffect]=currentState>
</div>
Here we have defined a div and applied the CSS style to make it a circle. Clicking on the div will invoke the changeState
method to switch the element’s state.
在這里,我們定義了一個div并應用CSS樣式使其成為一個圓圈。 單擊div將調用changeState
方法以切換元素的狀態。
Open the browser to see the animation in action as shown below:
打開瀏覽器以查看動畫,如下所示:
淡入和淡出動畫 (Fade In and Fade Out animation)
Sometimes we want to show animation while adding or removing an element on the DOM. We will see how to animate the addition and removal of an item to a list with a fade-in and fade-out effect.
有時我們想在添加或刪除DOM上的元素時顯示動畫。 我們將看到如何使用淡入和淡出效果為列表中的項目添加和移除動畫效果。
Add the following code inside the AnimationdemoComponent
class definition for adding and removing the element in a list:
在AnimationdemoComponent
類定義內添加以下代碼,以添加和刪除列表中的元素:
listItem = [];
list_order: number = 1;addItem() {var listitem = "ListItem " + this.list_order;this.list_order++;this.listItem.push(listitem);
}
removeItem() {this.listItem.length -= 1;
}
Add the following trigger definition in the animation property:
在animation屬性中添加以下觸發器定義:
trigger('fadeInOut', [state('void', style({opacity: 0})),transition('void <=> *', animate(1000)),
]),
Here we have defined the trigger fadeInOut
. When the element is added to the DOM it is a transition from void to wildcard (*) state. This is denoted using void =>
; *. When the element is removed from the DOM, it is a transition from wildcard (*) to void state. This is denoted using * =>
; void.
在這里,我們定義了觸發器fadeInOut
。 將元素添加到DOM時,它是從void到通配符(*)狀態的過渡。 用void =>
表示; *。 從DOM中刪除元素時,它是從通配符(*)到void狀態的過渡。 用ng * =>
表示; 虛空。
When we use the same animation timing for both directions of the animation, we use the shorthand syntax <
;=>. As defined in this trigger, the animation from voi
d => * and
* => void will take 1000ms to complete.
當我們在動畫的兩個方向上使用相同的動畫時間時,我們使用速記語法<
; =>。 如該觸發器中所定義, from voi
d =&g t; * and
的動畫t; * and
t; * and
* => void將需要1000毫秒才能完成。
Add the following HTML code in app.component.html file.
在app.component.html文件中添加以下HTML代碼。
<h3>Fade-In and Fade-Out animation</h3><button (click)="addItem()">Add List</button>
<button (click)="removeItem()">Remove List</button><div style="width:200px; margin-left: 20px"><ul><li *ngFor="let list of listItem" [@fadeInOut]>{{list}}</li></ul>
</div>
Here we are defining two buttons to add items to and remove them from the list. We are binding the fadeInOut trigger to the <
li> element, which will show a fade-in and fade-out effect while being added and removed from the DOM.
在這里,我們定義了兩個按鈕,用于向列表添加項目和從列表中刪除項目。 我們將fadeInOut觸發器綁定到<
li>元素,該元素在從DOM中添加和刪除時將顯示淡入和淡出效果。
Open the browser to see the animation in action as shown below:
打開瀏覽器以查看動畫,如下所示:
進入和離開動畫 (Enter and Leave animation)
When adding to the DOM, the element will enter the screen from the left. When deleting, the element will leave the screen from the right.
當添加到DOM時,該元素將從左側進入屏幕。 刪除時,該元素將從右側離開屏幕。
The transition from void => *
and * => void
is very common. Therefore, Angular provides aliases for these animations:
從void => *
和* => void
過渡非常普遍。 因此,Angular為這些動畫提供了別名:
- for void => * we can use ‘:enter’ 對于void => *,我們可以使用':enter'
- for * => void we can use ‘:leave’ 對于* => void,我們可以使用':leave'
The aliases make these transitions more readable and easier to understand.
別名使這些轉換更易于理解和理解。
Add the following trigger definition in the animation property:
在animation屬性中添加以下觸發器定義:
trigger('EnterLeave', [state('flyIn', style({ transform: 'translateX(0)' })),transition(':enter', [style({ transform: 'translateX(-100%)' }),animate('0.5s 300ms ease-in')]),transition(':leave', [animate('0.3s ease-out', style({ transform: 'translateX(100%)' }))])
])
Here we have defined the trigger EnterLeave
. The ‘:enter’ transition will wait for 300ms and then run for 0.5s with an ease-in effect. Whereas the ‘:leave transition will run for 0.3s with an ease-out effect.
在這里,我們定義了觸發器EnterLeave
。 ':enter'轉換將等待300毫秒,然后以緩入效果運行0.5 s。 而':leave過渡將運行0.3s并具有緩和效果。
Add the following HTML code in the app.component.html
file:
在app.component.html
文件中添加以下HTML代碼:
<h3>Enter and Leave animation</h3><button (click)="addItem()">Add List</button>
<button (click)="removeItem()">Remove List</button><div style="width:200px; margin-left: 20px"><ul><li *ngFor="let list of listItem" [@EnterLeave]="'flyIn'">{{list}}</li></ul>
</div>
Here we are defining two buttons to add items to and remove them from the list. We are binding the EnterLeave
trigger to the <
li> element that will show the enter and leave effect while being added and removed from the DOM.
在這里,我們定義了兩個按鈕,用于向列表添加項目和從列表中刪除項目。 我們將EnterLeave
觸發器綁定到<
li>元素,該元素將顯示在從DOM添加和刪除時的回車和離開效果。
Open the browser to see the animation in action as shown below:
打開瀏覽器以查看動畫,如下所示:
結論 (Conclusion)
In this article, we’ve learned about Angular 6 animations. We explored the concept of animation states and transitions. We also saw a few animations in action with the help of a sample application.
在本文中,我們了解了Angular 6動畫。 我們探索了動畫狀態和過渡的概念。 在示例應用程序的幫助下,我們還看到了一些動畫效果。
Please get the source code from GitHub and play around to get a better understanding.
請從GitHub獲取源代碼并進行嘗試以獲得更好的理解。
If you’re preparing for interviews, read my article on C# Coding Questions For Technical Interviews.
如果您正在準備面試,請閱讀有關C#編碼技術面試問題的文章。
也可以看看 (See Also)
ASP.NET Core — Using Highcharts With Angular 5
ASP.NET Core —在Angular 5中使用Highcharts
ASP.NET Core — CRUD Using Angular 5 And Entity Framework Core
ASP.NET Core —使用Angular 5和實體框架Core的CRUD
CRUD Operations With ASP.NET Core Using Angular 5 And ADO.NET
使用Angular 5和ADO.NET的ASP.NET Core的CRUD操作
ASP.NET Core — Getting Started With Blazor
ASP.NET Core — Blazor入門
CRUD Using Blazor with MongoDB
使用Blazor和MongoDB進行CRUD
Creating An SPA Using Razor Pages With Blazor
使用帶有Blazor的Razor頁面創建SPA
Originally published at https://ankitsharmablogs.com/
最初發布在https://ankitsharmablogs.com/
翻譯自: https://www.freecodecamp.org/news/how-to-use-animation-with-angular-6-675b19bc3496/
angular 動畫