אנימציות זוויתיות מוסברות בדוגמאות

מדוע להשתמש באנימציות?

רכיבי רשת מודרניים משתמשים לעתים קרובות באנימציות. גיליונות סגנון מדורגים (CSS) מפתחים זרועות עם הכלים ליצירת אנימציות מרשימות. מעברים נכסים, אנימציות בעלות שם ייחודי, מסגרות מפתח מרובות חלקים אפשריות באמצעות CSS. אפשרויות האנימציה הן אינסופיות בזכות CSS.

ביישום אינטרנט מודרני, אנימציה ממקדת את תשומת לב המשתמש. אנימציות טובות מבקשות להנחות את תשומת ליבו של המשתמש בצורה מספקת ופורה. אנימציות לא אמורות להוכיח את המשתמש כמעצבנות.

אנימציות מציעות משוב בצורה של תנועה. הם מראים למשתמש שהיישום מטפל באופן פעיל בבקשותיהם. משהו פשוט כמו לחיצה על לחצן גלוי או מטעין כאשר היישום חייב לטעון מושך את תשומת לב המשתמש.

אנימציות ממשיכות לצמוח יותר ויותר במקרה של אנגולר. גוגל מפתחת Angular תוך קידום הפילוסופיה לעיצוב חומרים. זה מעודד ממשקי משתמש תמציתיים (UI) בתוספת משוב משתמש מונפש. זה גורם ליישומי אינטרנט להרגיש קצת חיים ומהנים לשימוש.

קהילת Angular מפתחת ספריית יישומונים מרכזית בשם Material2. פרויקט זה מוסיף מגוון מודולים של יישומונים ל- Angular. ברובם יש אנימציות. כדי להבין כיצד הם עובדים, מאמר זה ממליץ על לימוד אנימציות CSS לפני המשך קריאה.

אנימציות זוויתיות היא הגרסה היעילה של המסגרת למה שמספק CSS באופן מקורי. CSS היא טכנולוגיית הליבה לאנימציות Angular המופיעות בדפדפן האינטרנט. CSS אינו מעבר לתחום מאמר זה. הגיע הזמן להתמודד חזיתית עם אנימציות זוויתיות.

הגדרת אנימציות

לפני ההנפשה, BrowserAnimationsModuleחייבים לכלול במערך הייבוא ​​של מודול הבסיס. זה זמין החל מ @angular/platform-browser/animations. NgModule זה מבטיח עבודות אנימציה עבור הפלטפורמה הנתונה. מאמר זה מניח את דפדפן האינטרנט הסטנדרטי עבור כל דוגמה.

אנימציות זוויתיות מכריזות על @Componentהמטא נתונים. @Componentמקשט כיתה כדי להבדיל אותה כמרכיב לזוויתית. המטא-נתונים שלו מכילים תצורות רכיבים כולל animations: []השדה. כל אלמנט מערך משדה זה מייצג טריגר אנימציה ( AnimationTriggerMetadata).

אנימציות בלעדיות לרכיב המארח שלהן באמצעות המטא-נתונים של הקשט. ניתן להשתמש באנימציות רק בתבנית הרכיב המארח. אנימציות אינן יורשות לילדי הרכיב. יש לעקוף זאת בקלות.

תמיד תוכל ליצור קובץ נפרד שמייצא מערך. כל מחלקת רכיבים יכולה לייבא מערך זה מראש קובץ המארח שלו. אסימון המערך המיובא נכנס למטא נתונים של האנימציה של הרכיב. חזור על תהליך זה עבור כל רכיב אחר הדורש את אותו מערך במטא נתונים האנימציות שלהם.

הקרנת תוכן מאפשרת לכם להחיל אנימציות על DOM של תוכן רכיב A (מודל אובייקט מסמך). רכיב B העוטף תוכן זה DOM יכול להקרין את התוכן לתבנית משלו. ברגע שזה קורה, האנימציות של רכיב A אינן שוללות. רכיב B משלב אנימציות של A באמצעות הקרנת תוכן.

בסדר. אתה יודע כיצד להגדיר אנימציות ואיפה להכריז עליהן. יישום הוא השלב הבא.

שיטות אנימציה

אנימציות זוויתיות משתמשות בסדרה של שיחות שיטה שניתן לייבא מהן @angular/animations. כל אלמנט @Componentבמערך האנימציות מתחיל כשיטה אחת. טיעוניו נפרשים כרצף של קריאות שיטה מסדר גבוה. הרשימה הבאה מציגה כמה מהשיטות המשמשות לבניית אנימציות זוויתיות.

  • 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

אמנם יש בהחלט שיטות נוספות לבחירה, אך חמש השיטות הללו מטפלות ביסודות. ניסיון להבין את שיטות הליבה הללו כרשימה לא עוזר במיוחד. הסברים מתבליטים ואחריהם דוגמה יבינו זאת בצורה טובה יותר.

טריגר (בורר: מחרוזת, AnimationMetadata [])

trigger(...)השיטה מתמצת אלמנט בודד של הנפשה בתוך מערך אנימציות.

הטיעון הראשון של השיטה selector: stringתואם [@selector]למאפיין החבר. זה פועל כמו הנחיית מאפיינים בתבנית הרכיב. למעשה הוא מחבר את אלמנט האנימציה לתבנית באמצעות בורר תכונות.

הטיעון השני הוא מערך המכיל רשימה של שיטות אנימציה ישימות. trigger(...)שומר אותו לחלוטין במערך בודד.

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

state(...)השיטה מגדירה את המצב הסופי של האנימציה. הוא מחיל רשימה של מאפייני CSS על אלמנט היעד לאחר סיום אנימציה. זאת כך ש- CSS של אלמנט האנימציה תואם לרזולוציית האנימציה.

הארגומנט הראשון תואם את ערך הנתונים הקשורים לכריכת האנימציה. כלומר, הערך הכרוך [@selector]בתבנית תואם לארגומנט הראשון של a state(...). ערך הנתונים קובע את המצב הסופי. שינוי הערך קובע את אמצעי האנימציה (ראה transition(...)).

הטיעון השני מארח את סגנונות ה- CSS החלים על אלמנט שלאחר אנימציה. סגנונות עוברים פנימה על ידי הפעלת style(...)ולהעביר לטיעון את הסגנונות הרצויים כחפץ.

רשימת אפשרויות אופציונלית תופסת את הטיעון השלישי. state(...)אפשרויות ברירת המחדל צריכות להישאר ללא שינוי אלא אם כן נימקו אחרת.

סגנון (CSSKeyValues: אובייקט)

יתכן ששמתם לב AnimationStyleMetadataכמה פעמים ברשימה הקודמת. style(...)הרכיב חוזר מסוג זה בדיוק מטה. בכל מקום שבו סגנונות CSS חלים, על style(...)השיטה להפעיל. אובייקט המכיל סגנונות CSS עומד על טיעונו.

כמובן, סגנונות המצויירים ב- CSS מועברים style(...)לשיטת Angular . נכון, שום דבר בלתי אפשרי עבור CSS הופך פתאום לאפשרי באנימציות Angular.

אנימציה (תזמון: מחרוזת | מספר, AnimationStyleMetadata | אנימציה KeyframesMetadata)

animate(...)הפונקציה מקבלת ביטוי עיתוי כמו הטענה הראשונה שלה. טיעון זה מתארך בזמן, צעדים ו / או מעכב את האנימציה של השיטה. טיעון זה מקבל ביטוי מספר או מחרוזת. העיצוב מוסבר כאן.

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