angular 动画_如何在Angular 6中使用动画

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为一个元素定义了三种不同的状态:

  1. 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

  2. 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.

    通配符状态-这也称为元素的默认状态。 为此元素定义的样式适用于该元素,而不管其当前的动画状态如何。 要在我们的代码中定义此状态,我们使用*符号。

  3. 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 Terminal. 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 <div> 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 <div> 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 <div> element and applied the animation trigger changeDivSize 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 void =&gt; * 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)

Originally published at https://ankitsharmablogs.com/

最初发布在https://ankitsharmablogs.com/

翻译自: https://www.freecodecamp.org/news/how-to-use-animation-with-angular-6-675b19bc3496/

angular 动画

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值