Näidetega selgitatud nurkanimatsioonid

Miks kasutada animatsioone?

Kaasaegsed veebikomponendid kasutavad sageli animatsioone. CSS (CSS) pakuvad arendajatele muljetavaldavate animatsioonide loomiseks vajalikke tööriistu. Omaduste üleminekud, ainulaadse nimega animatsioonid, mitmeosalised võtmekaadrid on CSS-iga võimalikud. Animeeritavad võimalused on tänu CSS-ile lõputud.

Kaasaegses veebirakenduses keskendub animatsioon kasutaja tähelepanu. Head animatsioonid püüavad suunata kasutaja tähelepanu rahuldavalt ja produktiivselt. Animatsioonid ei tohiks osutuda kasutajale tüütuks.

Animatsioonid pakuvad tagasisidet liikumise vormis. Need näitavad kasutajale, et rakendus tegeleb nende taotlustega aktiivselt. Midagi nii lihtsat kui nähtav nupuvajutus või laadur, kui rakendus peab laadima, köidab kasutaja tähelepanu.

Animatsioonid kasvavad Angulari puhul järjest aktuaalsemaks. Google arendab Angulari, samal ajal propageerides materiaalse disaini filosoofiat. See julgustab lühikesi kasutajaliideseid (UI), millele on lisatud animeeritud kasutajate tagasiside. See muudab veebirakendused mõnevõrra elusaks ja lõbusaks.

Nurgakogukond arendab põhilist vidinate kogu nimega Material2. See projekt lisab Angularile mitmesuguseid vidinamooduleid. Enamikul neist on animatsioone. Nende toimimise mõistmiseks soovitab see artikkel CSS-i animatsioone enne selle lugemist uurida.

Nurgaanimatsioonid on raamistiku sujuvam versioon sellest, mida CSS loomulikult pakub. CSS on veebibrauseris toimuvate nurgaanimatsioonide põhitehnoloogia. CSS ei kuulu selle artikli reguleerimisalasse. Aeg on nurkanimatsioonidega pea ees tegeleda.

Animatsioonide seadistamine

Enne animeerimist BrowserAnimationsModulepeab must sisaldama juurmooduli impordimassiivi. See on saadaval aadressilt @angular/platform-browser/animations. See NgModule tagab animatsioonide töö antud platvormi jaoks. Selles artiklis eeldatakse iga näite jaoks tavalist veebibrauserit.

Nurgaanimatsioonid deklareerivad @Componentmetaandmetes. @Componentkaunistab klassi, et eristada seda kui nurga komponenti. Selle metaandmed sisaldavad komponentide konfiguratsioone, sealhulgas animations: []välja. Iga selle massiivi element tähistab animatsiooni päästikut ( AnimationTriggerMetadata).

Animatsioonid on dekoreerija metaandmete kaudu eksklusiivsed ainult nende hostkomponendile. Animatsioone saab kasutada ainult hostikomponendi mallis. Animatsioonid ei ole komponendi lastele päritavad. Selle jaoks on lihtne lahendus.

Alati võiksite luua eraldi faili, mis eksportib massiivi. Iga komponentklass saab selle massiivi oma hostifaili ülaosast importida. Imporditud massiivi märgis läheb seejärel komponendi animatsioonide metaandmetesse. Korrake seda protsessi kõigi muude komponentide jaoks, mis vajavad sama massiivi oma animatsioonide metaandmetes.

Sisu projektsioon võimaldab teil animatsioone rakendada A komponendi sisule DOM (Document Object Model). Komponent B, pakkides selle sisu, saab DOM sisu projitseerida oma malli. Kui see juhtub, ei tühista komponendi A animatsioone. Komponent B sisaldab A animatsioone sisulise projektsiooni kaudu.

OKEI. Teate, kuidas animatsioone seadistada ja kuhu need deklareerida. Järgmine samm on rakendamine.

Animatsioonimeetodid

Nurgaanimatsioonides kasutatakse rea meetodikõnesid, mida saab importida @angular/animations. @ComponentAnimatsioonimassiivi iga element algab ühe meetodina. Selle argumendid avanevad kõrgema järgu meetodikutsete jadana. Järgmises loendis on toodud mõned nurganimatsioonide loomisel kasutatavad meetodid.

  • trigger(selector: string, AnimationMetadata[])

naaseb AnimationTriggerMetadata

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

naaseb AnimationStateMetadata

  • style(CSSKeyValues: object)

naaseb AnimationStyleMetadata

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

naaseb AnimationAnimateMetadata

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

naaseb AnimationTransitionMetadata

Ehkki valida on kindlasti rohkem meetodeid, saavad need viis meetodit hakkama põhitõdedega. Püüdmine mõista neid põhimeetodeid loendina ei aita eriti. Bullet-by-bullet-seletused, millele järgneb näide, mõistavad seda paremini.

päästik (valija: string, AnimationMetadata [])

trigger(...)Meetod kapseloi ühe elemendi animatsiooni sees animatsioone massiiv.

Meetodi esimene argument selector: stringsobib [@selector]liikme atribuudiga. See toimib komponendimallis nagu atribuudidirektiiv. Sisuliselt ühendab see animatsioonielemendi malliga atribuutide valija kaudu.

Teine argument on massiiv, mis sisaldab loendit animeeritavatest meetoditest. See trigger(...)hoiab seda kokku ühe massiivina.

olek (andmed: string, AnimationStyleMetadata, valikud ?: objekt)

state(...)Meetodiga määratakse lõplikku seisu animatsiooni. Pärast animatsiooni lõppu rakendab see sihtelemendile CSS-i omaduste loendit. See on nii, et animeeritud elemendi CSS vastab animatsiooni eraldusvõimele.

Esimene argument vastab animatsiooni sidumisega seotud andmete väärtusele. See tähendab, et [@selector]malliga seotud väärtus ühtib a-i esimese argumendiga state(...). Andmete väärtus määrab lõpliku oleku. Väärtuse muutmine määrab animatsiooni vahendid (vt transition(...)).

Teine argument sisaldab CSS-i stiile, mis kehtivad elemendi post-animatsioonile. Stiilid lähevad edasi, kutsudes style(...)ja argumenteerides soovitud stiilid objektina.

Valikute loend hõlmab valikuliselt kolmandat argumenti. Vaikevalikud state(...)peaksid muutumatuks jääma, kui pole teisiti põhjendatud.

stiil (CSSKeyValues: objekt)

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

See hõlmab Angulariga animeerimise põhitõdesid. Angular muudab animatsioonide seadistamise Angular CLI abil väga lihtsaks. Esimese animatsiooniga alustamiseks on vaja ainult ühte komponenti. Pidage meeles, et animatsioonid hõlmavad komponendi malli. Eksportige oma ülemineku massiiv eraldi failist, kui kavatsete seda kasutada mitme komponendi vahel.

Iga animatsiooni utiliit / meetod eksporditakse @angular/animations. Nad kõik töötavad koos, et pakkuda CSS-ist inspireeritud tugevat animatsioonisüsteemi. Lisaks sellele, mida see artikkel võiks hõlmata, on veel meetodeid.

Nüüd, kui teate põhitõdesid, uurige julgelt allpool olevaid linke nurkanimatsioonide kohta.

Lisateave nurkanimatsioonide kohta:

  • Nurgadokumentatsioon
  • Kuidas kasutada animatsiooni nurga 6 abil