כיצד להשתמש באנימציה עם Angular 6

מבוא

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

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

נשתמש בקוד Visual Studio לצורך ההדגמה שלנו.

תנאים מוקדמים

התקן קוד VS ו- CLI Angular.

אם אתה לא חדש ב- Angular, עיין במאמר הקודם שלי תחילת העבודה עם Angular 6.0 להגדרת סביבת הפיתוח של Angular 6 במחשב שלך.

קוד מקור

הורד את קוד המקור מ- GitHub.

הבנת מדינות אנימציה זוויתיות

אנימציה כוללת מעבר ממצב אחד של אלמנט למצב אחר. זווית מגדירה שלושה מצבים שונים עבור אלמנט:

  1. מצב ריק - מייצג את מצב היסוד שאינו חלק מה- DOM. מצב זה מתרחש כאשר אלמנט נוצר אך טרם ממוקם ב- DOM או שהאלמנט מוסר מה- DOM. מצב זה שימושי כאשר אנו רוצים ליצור אנימציה בזמן הוספה או הסרה של אלמנט מה- DOM שלנו. כדי להגדיר מצב זה בקוד שלנו אנו משתמשים במילת המפתח void.
  2. מצב התווים כלליים - זה ידוע גם כמצב ברירת המחדל של האלמנט. הסגנונות המוגדרים למצב זה חלים על האלמנט ללא קשר למצב האנימציה הנוכחי שלו. כדי להגדיר מצב זה בקוד שלנו אנו משתמשים *בסמל.
  3. מצב מותאם אישית - זהו המצב המותאם אישית של האלמנט ויש להגדירו במפורש בקוד. כדי להגדיר מצב זה בקוד שלנו, אנו יכולים להשתמש בכל שם מותאם אישית לבחירתנו.

תזמון מעבר לאנימציה

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

Angular מספק את שלושת מאפייני התזמון הבאים:

מֶשֶׁך

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

  • שימוש בערך מספר שלם לייצוג הזמן באלפיות השנייה. למשל 500
  • שימוש בערך מחרוזת לייצוג הזמן באלפיות השנייה. למשל - '500ms'
  • שימוש בערך מחרוזת לייצוג הזמן בשניות. למשל - '0.5 שניות'

לְעַכֵּב

מאפיין זה מייצג את משך הזמן בין הדק ההנפשה לתחילת המעבר בפועל. מאפיין זה עוקב אחר תחביר זהה לזה של משך הזמן. כדי להגדיר את העיכוב, עלינו להוסיף את ערך ההשהיה לאחר ערך המשך בפורמט מחרוזת - 'Duration Delay'. עיכוב הוא מאפיין אופציונלי.

לדוגמה:

  • '0.3s 500ms'. המשמעות היא שהמעבר ימתין ל- 500ms ואז יפעל ל- 0.3s.

הֲפָגָה

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

לדוגמה:

  • '0.3s 500ms gemak-in' - המשמעות היא שהמעבר ימתין ל- 500ms ואז יפעל ל- 0.3s (300ms) עם אפקט הקלות.
  • '300ms קלות'. - המשמעות היא שהמעבר יעבור למשך 300ms (0.3s) עם אפקט הקלה.

יצירת יישום Angular 6

פתח את שורת הפקודה במחשב שלך ובצע את קבוצת הפקודות הבאות:

  • mkdir ngAnimationDemo
  • cd ngAnimationDemo
  • ng חדש. אנימציה

פקודות אלה ייצרו ספריה עם השם ngAnimationDemoואז ייצרו יישום Angular עם השם ngAnimationבתוך אותה ספריה.

פתח את אפליקציית ngAnimation באמצעות קוד VS. עכשיו ניצור את הרכיב שלנו.

נווט אל View >> Integrated Terminal. פעולה זו תפתח חלון מסוף בקוד VS.

בצע את הפקודה הבאה כדי ליצור את הרכיב.

ng g c animationdemo

זה ייצור את הרכיב שלנו animationdemoבתוך /src/appהתיקיה.

כדי להשתמש באנימציית Angular עלינו לייבא BrowserAnimationsModuleשהוא מודול ספציפי לאנימציה ביישום שלנו. פתח את הקובץ app.module.ts והכלל את הגדרת הייבוא ​​כמוצג להלן:

import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; // other import definitions @NgModule({ imports: [BrowserAnimationsModule // other imports]})

הבנת תחביר האנימציה הזוויתי

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

@Component({ // other component properties. animations: [ trigger('triggerName'), [ state('stateName', style()) transition('stateChangeExpression', [Animation Steps]) ] ] })

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

לכל פונקציית מצב יש "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.

These functions trigger, and state and transition are defined in the @angular/animations module. Hence, we need to import this module in our component.

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:

This will apply the trigger changeSize to the iv> element.

Let us create a few animations to get a better understanding of the Angular animation concepts.

Change Size Animation

We will create an animation to change the size of a iv> element on a button click.

Open the animationdemo.component.ts file and add the following import definition:

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.

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.

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:

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.

Open animationdemo.component.html file and add the following code:

Change the div size

Change Size

We have defined a button which will invoke the changeState function when clicked. We have defined a iv> element and applied the animation tr igger changeDivSize to it. When we click on the button it will flip the state o f the element and its size will change with a transition effect.

Before executing the application, we need to include the reference to our Animationdemo component inside the app.component.html file.

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:

To execute the code run the ng serve command in the VS code terminal window. After running this command, it will ask to open //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.

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:

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.

Add the following HTML code in the app.component.html file:

Balloon Effect

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.

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.

Add the following code inside the AnimationdemoComponent class definition for adding and removing the element in a list:

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:

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.

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.

Add the following HTML code in app.component.html file.

Fade-In and Fade-Out animation

Add List Remove List
  • {{list}}

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.

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.

The transition from void => * and * => void is very common. Therefore, Angular provides aliases for these animations:

  • for void => * we can use ‘:enter’
  • for * => void we can use ‘:leave’

The aliases make these transitions more readable and easier to understand.

Add the following trigger definition in the animation property:

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.

Add the following HTML code in the app.component.html file:

Enter and Leave animation

Add List Remove List
  • {{list}}

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.

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.

Please get the source code from GitHub and play around to get a better understanding.

If you’re preparing for interviews, read my article on C# Coding Questions For Technical Interviews.

See Also

  • ASP.NET Core — Using Highcharts With Angular 5
  • ASP.NET Core — CRUD Using Angular 5 And Entity Framework Core
  • CRUD Operations With ASP.NET Core Using Angular 5 And ADO.NET
  • ASP.NET Core — Getting Started With Blazor
  • CRUD Using Blazor with MongoDB
  • Creating An SPA Using Razor Pages With Blazor

Originally published at //ankitsharmablogs.com/