例で説明された角度アニメーション

なぜアニメーションを使うのですか?

最新のWebコンポーネントは、アニメーションを頻繁に使用します。カスケードスタイルシート(CSS)は、印象的なアニメーションを作成するためのツールを開発者に提供します。CSSを使用すると、プロパティの遷移、一意の名前のアニメーション、マルチパートキーフレームが可能です。CSSのおかげで、アニメート可能な可能性は無限大です。

最新のWebアプリケーションでは、アニメーションがユーザーの注意を集中させます。優れたアニメーションは、満足のいく生産的な方法でユーザーの注意を導くことを目的としています。アニメーションは、ユーザーにとって煩わしいものであってはなりません。

アニメーションは、動きの形でフィードバックを提供します。これらは、アプリケーションがアクティブにリクエストを処理していることをユーザーに示します。アプリケーションをロードする必要があるときに、目に見えるボタンを押すかローダーを押すだけの単純なものが、ユーザーの注意を引き付けます。

Angularの場合、アニメーションの関連性はますます高まっています。Googleは、マテリアルデザインの哲学を推進しながらAngularを開発しています。アニメーション化されたユーザーフィードバックで補完された簡潔なユーザーインターフェイス(UI)を奨励します。これにより、Webアプリケーションはやや生き生きとしていて楽しく使用できるようになります。

Angularコミュニティは、Material2と呼ばれるコアウィジェットライブラリを開発しています。このプロジェクトは、さまざまなウィジェットモジュールをAngularに追加します。それらのほとんどはアニメーションを備えています。それらがどのように機能するかを理解するために、この記事では、読む前にCSSアニメーションを学習することをお勧めします。

Angularアニメーションは、CSSがネイティブに提供するもののフレームワークの合理化されたバージョンです。CSSは、Webブラウザー内で発生するAngularアニメーションのコアテクノロジーです。ただし、CSSはこの記事の範囲を超えています。Angularアニメーションに正面から取り組む時が来ました。

アニメーションの設定

アニメーション化する前BrowserAnimationsModuleに、ルートモジュールのインポート配列に含める必要があります。から入手できます@angular/platform-browser/animations。このNgModuleは、特定のプラットフォームでアニメーションが機能することを保証します。この記事では、各例の標準Webブラウザーを想定しています。

角度のあるアニメーションは、@Componentメタデータ内で宣言します。@Componentクラスを装飾して、Angularのコンポーネントとして区別します。そのメタデータには、animations: []フィールドを含むコンポーネント構成が含まれています。このフィールドの各配列要素は、アニメーショントリガー(AnimationTriggerMetadata)を表します。

アニメーションは、デコレータのメタデータを介してホストコンポーネント専用です。アニメーションは、ホストコンポーネントのテンプレートでのみ使用できます。アニメーションはコンポーネントの子に継承されません。これには簡単な回避策があります。

配列をエクスポートする別のファイルをいつでも作成できます。どのコンポーネントクラスも、その配列をホストファイルの先頭からインポートできます。インポートされた配列トークンは、コンポーネントのアニメーションメタデータに入ります。アニメーションメタデータに同じ配列を必要とする他のコンポーネントについて、このプロセスを繰り返します。

コンテンツプロジェクションを使用すると、コンポーネントAのコンテンツDOM(ドキュメントオブジェクトモデル)にアニメーションを適用できます。このコンテンツDOMをラップするコンポーネントBは、コンテンツを独自のテンプレートに投影できます。一度実行すると、コンポーネントAのアニメーションは無効になりません。コンポーネントBは、コンテンツの投影を通じてAのアニメーションを組み込んでいます。

OK。アニメーションを設定する方法と宣言する場所を知っています。次のステップは実装です。

アニメーション手法

角度アニメーションは、からインポート可能な一連のメソッド呼び出しを使用し@angular/animationsます。@Componentアニメーション配列の各要素は、単一のメソッドとして始まります。その引数は、一連の高次メソッド呼び出しとして解明されます。次のリストは、Angularアニメーションの作成に使用されるいくつかの方法を示しています。

  • trigger(selector: string, AnimationMetadata[])

戻り値 AnimationTriggerMetadata

  • state(data: string, AnimationStyleMetadata, options?: object)

戻り値 AnimationStateMetadata

  • style(CSSKeyValues: object)

戻り値 AnimationStyleMetadata

  • animate(timing: string|number, AnimationStyleMetadata|KeyframesMetadata)

戻り値 AnimationAnimateMetadata

  • transition(stateChange: string, AnimationMetadata|AnimationMetadata[], options?: object)

戻り値 AnimationTransitionMetadata

確かに選択できる方法は他にもありますが、これら5つの方法で基本を処理します。これらのコアメソッドをリストとして理解しようとしても、あまり役に立ちません。箇条書きごとの説明とそれに続く例は、それをよりよく理解するでしょう。

trigger(selector:string、AnimationMetadata [])

このtrigger(...)メソッドは、アニメーションの単一要素をアニメーション配列内にカプセル化します。

The method’s first argument selector: string matches the [@selector] member attribute. It acts like an attribute directive in the component template. It essentially connects the animation element to the template through an attribute selector.

The second argument is an array containing a list of applicable animation methods. The trigger(...) keeps it altogether in a single array.

state(data: string, AnimationStyleMetadata, options?: object)

The state(...) method defines the final state of the animation. It applies a list of CSS properties to the target element after an animation concludes. This is so the animated element’s CSS matches the animation’s resolution.

The first argument matches the value of the data bound to the animation binding. That is, the value bound to [@selector] in the template matches against first argument of a state(...). The data’s value determines the final state. The changing of the value determines the means of animation (see transition(...)).

The second argument hosts the CSS styles that apply to an element post-animation. Styles get passed in by invoking style(...) and passing into its argument the desired styles as an object.

A list of options optionally occupies the third argument. The default state(...) options should remain unchanged unless reasoned otherwise.

style(CSSKeyValues: object)

You may have noticed AnimationStyleMetadata several times in the previous list. The style(...) component returns this exact type of metadata. Wherever CSS styles apply, the style(...) method must invoke. An object containing CSS styles stands-in for its argument.

Of course, styles animatable in CSS carry over into the Angular style(...) method. Granted, nothing impossible for CSS becomes suddenly possible with Angular animations.

animate(timing: string|number, AnimationStyleMetadata|AnimationKeyframesMetadata)

The animate(...) function accepts a timing expression as its first argument. This argument times, paces, and/or delays the method’s animation. This argument accepts either a number or string expression. The formatting is explained here.

The second argument of animate(...) is the CSS property warranting the animation. This takes the form of the style(...) method which returns AnimationStyleMetadata. Think of animate(...) as the method that initiates the animation.

A series of keyframes can also apply to the second argument. Keyframes is a more advanced option that this article explains later on. Keyframes distinguish various sections of the animation.

animate(...) may not receive a second argument. In that case, the method’s animation timing only applies to the CSS reflected in the state(...) methods. Property changes in the trigger’s state(...) methods will animate.

transition(changExpr: string, AnimationMetadata|AnimationMetadata[], options?: object)

animate(...) initiates an animation while transition(...) determines which animation initiates.

The first argument consists of a unique form of micro-syntax. It denotes a change in state (or change in data) taking place. The data bound to the template animation binding ([selector]="value") determines this expression. The upcoming section titled “Animation State” explains this concept a bit further.

The second argument of transition(...) comprises AnimationMetadata (returned by animate(...)). The argument accepts either an array of AnimationMetadata or a single instance.

The first argument’s value matches against the value of the data bound in the template ([selector]="value") . If a perfect match occurs, the argument evaluates successfully. The second argument then initiates an animation in response to the success of the first.

A list of options optionally occupies the third argument. The default transition(...) options should remain unchanged unless reasoned otherwise.

Animation Example

import { Component, OnInit } from '@angular/core'; import { trigger, state, style, animate, transition } from '@angular/animations'; @Component({ selector: 'app-example', template: ` 

Click the button to change its color!

Toggle Me! // animation binding `, animations: [ // metadata array trigger('toggleClick', [ // trigger block state('true', style({ // final CSS following animation backgroundColor: 'green' })), state('false', style({ backgroundColor: 'red' })), transition('true => false', animate('1000ms linear')), // animation timing transition('false => true', animate('1000ms linear')) ]) ] // end of trigger block }) export class ExampleComponent { isGreen: string = 'true'; toggleIsCorrect() { this.isGreen = this.isGreen === 'true' ? 'false' : 'true'; // change in data-bound value } }

The above example performs a very simple color swap with each button click. Of course, the color transitions quickly in a linear fade as per animate('1000ms linear'). The animation binds to the button by matching the first argument of trigger(...) to the [@toggleClick] animation binding.

The binding binds to the value of isGreen from the component class. This value determines the resulting color as set by the two style(...) methods inside the trigger(...) block. The animation binding is one-way so that changes to isGreen in the component class notify the template binding. That is, the animation binding [@toggleClick].

The button element in the template also has a click event bound to it. Clicking the button causes isGreen to toggle values. This changes the component class data. The animation binding picks up on this and invokes its matching trigger(...) method. The trigger(...) lies within the animations array of the component’s metadata. Two things occur upon the trigger’s invocation.

The first occurrence concerns the two state(...) methods. The new value of isGreen matches against a state(...) method’s first argument. Once it matches, the CSS styles of style(...) apply to the final state of the animation binding’s host element. `The final state takes effect following all animation.

Now for the second occurrence. The data change that invoked the animation binding compares across the two transition(...) methods. One of them matches the change in data to their first argument. The first button click caused isGreen to go from ‘true’ to ‘false’ (‘true => false’). That means the first transition(...) method activates its second argument.

The animate(...) function corresponding the successfully evaluated transition(...) method initiates. This method sets the duration of the animated color fade along with the fade’s pacing. The animation executes and the button fades to red.

This process can happen any number of times following a button click. The backgroundColor of the button will cycle between green and red in a linear fade.

Animation State

The transition(...) micro-syntax is worth addressing in detail. Angular determines animations and their timing by evaluating this syntax. There exists the following state transitions. They model a changes in data bound to an animation binding.

  • ‘someValue’ => ‘anotherValue’

An animation trigger where the bound data changes from ‘someValue’ to ‘anotherValue’.

  • ‘anotherValue’ => ‘someValue’

An animation trigger where the bound data changes from ‘anotherValue’ to ‘someValue’.

  • ‘someValue’ ‘anotherValue’

Data changes from ‘someValue` to ‘anotherValue’ or vice versa.

There also exists void and * states. void indicates that the component is either entering or leaving the DOM. This is perfect for entry and exit animations.

  • ‘someValue’ => void : host component of bound data is leaving the DOM
  • void => ‘someValue’ : host component of bound data is entering the DOM

* denotes a wildcard state. Wildcard states can interpret to “any state”. This includes void plus any other change to the bound data.

Keyframes

This article touched on the basics for animating Angular applications. Advanced animation techniques exist alongside these basics. Grouping together keyframes is one such technique. Its inspired from the @keyframes CSS rule. If you have worked with CSS @keyframes, you already understand how keyframes in Angular work. It becomes just a matter of syntax

The keyframes(...) method imports from @angular/animations. It passes into the second argument of animate(...) instead of the typical AnimationStyleMetadata. The keyframes(...) method accepts one argument as an array of AnimationStyleMetadata. This can also be referred to as an array of style(...) methods.

Each keyframe of the animation goes inside the keyframes(...) array. These keyframe elements are style(...) methods supporting the offset property. offset indicates a point in the animation’s duration where its accompanying style properties should apply. Its value spans from 0 (animation start) to 1 (animation end).

import { Component } from '@angular/core'; import { trigger, state, style, animate, transition, keyframes } from '@angular/animations'; @Component({ selector: 'app-example', styles: [ `.ball { position: relative; background-color: black; border-radius: 50%; top: 200px; height: 25px; width: 25px; }` ], template: ` 

Arcing Ball Animation

Arc the Ball! `, animations: [ trigger('animateArc', [ state('true', style({ left: '400px', top: '200px' })), state('false', style({ left: '0', top: '200px' })), transition('false => true', animate('1000ms linear', keyframes([ style({ left: '0', top: '200px', offset: 0 }), style({ left: '200px', top: '100px', offset: 0.50 }), style({ left: '400px', top: '200px', offset: 1 }) ]))), transition('true => false', animate('1000ms linear', keyframes([ style({ left: '400px', top: '200px', offset: 0 }), style({ left: '200px', top: '100px', offset: 0.50 }), style({ left: '0', top: '200px', offset: 1 }) ]))) ]) ] }) export class ExampleComponent { arc: string = 'false'; toggleBounce(){ this.arc = this.arc === 'false' ? 'true' : 'false'; } }

The main difference of the above example compared to the other example is the second argument of animate(...). It now contains a keyframes(...) method hosting an array of animation keyframes. While the animation itself is also different, the technique to animate is similar.

Clicking the button causes the button to arc across the screen. The arc moves as per the keyframes(...) method’s array elements (keyframes). At the animation’s mid-point (offset: 0.50), the ball changes trajectory. It descends to its original height as it continues across the screen. Clicking the button again reverses the animation.

left and top are animatable properties after setting position: relative; for the element. The transform property can perform similar movement-based animations. transform is an expansive yet fully animatable property.

Any number of keyframes can existing between offset 0 and 1. Intricate animation sequences take the form of keyframes. They are one of many advanced techniques in Angular animations.

Animations With Host Binding

You will undoubtedly come across the situation where you want to attach an animation to the HTML element of a component itself, instead of an element in the component’s template. This requires a little more effort since you can’t just go into the template HTML and attach the animation there. Instead, you’ll have to import HostBinding and utilize that.

The minimal code for this scenario is shown below. I’ll re-use the same animation condition for the code above for consistency and I don’t show any of the actual animation code since you can easily find that above.

import { Component, HostBinding } from '@angular/core'; @Component({ ... }) export class ExampleComponent { @HostBinding('@animateArc') get arcAnimation() { return this.arc; } }

The idea behind animating the host component is pretty much the same as animating a element from the template with the only difference being your lack of access to the element you are animating. You still have to pass the name of the animation (@animateArc) when declaring the HostBinding and you still have to return the current state of the animation (this.arc). The name of the function doesn’t actual matter, so arcAnimation could have been changed to anything, as long as it doesn’t clash with existing property names on the component, and it would work perfectly fine.

Conclusion

This covers the basics of animating with Angular. Angular makes setting up animations very easy using the Angular CLI. Getting started with your first animation only requires a single component class. Remember, animations scope to the component’s template. Export your transitions array from a separate file if you plan to use it across multiple components.

Every animation utility/method exports from @angular/animations. They all work together to provide a robust system of animation inspired from CSS. There are more methods beyond what this article could cover.

Now that you know the basics, feel free to explore the links below for more on Angular animations.

More info on Angular Animations:

  • Angular Documentation
  • How to use animation with Angular 6