How Can I Animate A Div In Angular
Introduction
Blitheness is defined equally the transition from an initial state to a terminal state. It is an integral part of whatever mod web application. Animation not simply helps the states create a great UI but information technology also makes the application interesting and fun to utilize. A well-structured blitheness keeps the user engaged with the application and enhances the user experience.
Athwart allows us to create animations which provides usa similar native performance as CSS animations. In this article, we will larn how we can create blitheness using Angular 6.
Nosotros volition use Visual Studio Lawmaking for our demo.
Prerequisites
Install VS code and Angular CLI.
If you are new to Angular, then refer to my previous article Getting Started With Angular 6.0 to gear up the Angular 6 development surround on your machine.
Source Code
Download the source code from GitHub.
Understanding Angular Animation States
Animation involves transition from one country of an element to some other country. Angular defines three unlike states for an element:
- Void country — represents the land of an chemical 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 lawmaking we use the keyword
void. - The wildcard state — This is also known as the default land of the element. The styles defined for this country are applicable to the chemical element regardless of its current animation state. To define this land in our code nosotros utilise the
*symbol. - Custom state — This is the custom country of the element and it needs to exist divers explicitly in the code. To define this state in our code, nosotros can utilize any custom name of our selection.
Animation Transition Timing
To show the animation transition from one state to some other, we define animation transition timing in our application.
Angular provides the following three timing properties:
Duration
This holding represents the time our animation takes to complete from start (initial state) to finish (terminal state). We tin can define the duration of animation in the following iii ways:
- Using an integer value to correspond the time in milliseconds. Eastward.thou.- 500
- Using a string value to stand for the fourth dimension in milliseconds. E.m. — '500ms'
- Using a cord value to represent the time in seconds. East.thousand. — '0.5s'
Filibuster
This belongings represents the duration between the blitheness trigger and the beginning of the bodily transition. This belongings also follows the same syntax as duration. To ascertain the filibuster, we need to add the delay value later on the duration value in a cord format — ' Duration Delay'. Delay is an optional property.
For example:
- '0.3s 500ms'. This ways the transition will expect for 500ms and then run for 0.3s.
Easing
This property represents how the blitheness accelerates or decelerates during its execution. We tin can define the easing by adding information technology as the third variable in the string after duration and delay. If the delay value is not nowadays, then easing will exist the second value. This is also an optional belongings.
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.
- '300ms ease-out'. — This means the transition will run for 300ms (0.3s) with ease-out effect.
Creating the Angular 6 application
Open command prompt in your car and execute the post-obit set of commands:
- mkdir ngAnimationDemo
- cd ngAnimationDemo
- ng new ngAnimation
These commands will create a directory with the name ngAnimationDemo and and so create an Athwart application with the proper name ngAnimation inside that directory.
Open the ngAnimation app using VS code. Now we volition create our component.
Navigate to View >> Integrated Terminal. This will open a terminal window in VS Code.
Execute the following command to create the component.
ng g c animationdemo This will create our component animationdemo within the /src/app folder.
To use Angular animation we need to import BrowserAnimationsModule which is an blitheness-specific module in our application. Open the app.module.ts file and include the import definition as shown below:
import { BrowserAnimationsModule } from '@athwart/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'due south metadata. The syntax for the animation is shown below:
@Component({ // other component properties. animations: [ trigger('triggerName'), [ state('stateName', style()) transition('stateChangeExpression', [Blitheness Steps]) ] ] }) Hither we will use a property called animations. This property will have an array every bit input. The array contains i or more than "trigger". Each trigger has a unique name and an implementation. The state and transitions for our blitheness demand to exist defined in the trigger implementation.
Each state function has a "stateName" defined to uniquely identify the state and a style function to show the manner of the element in that state.
Each transition function has a stateChangeExpression defined to show the modify of the country of an element and the corresponding array of blitheness steps to show how the transition will take place. We can include multiple trigger functions inside the animation property every bit 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 proper noun in the element definition. Include the trigger proper name followed by @ symbol in the chemical element tag. Refer to the sample code below:
<div @changeSize></div> This will apply the trigger changeSize to the <d4> chemical element.
Let us create a few animations to get a better understanding of the Athwart animation concepts.
Change Size Blitheness
We volition create an animation to modify the size of a <div> element on a button click.
Open up the animationdemo.component.ts file and add together the following import definition:
import { trigger, state, manner, animate, transition } from '@angular/animations'; Add together the following animation property definition in the component metadata:
animations: [ trigger('changeDivSize', [ state('initial', style({ backgroundColor: 'dark-green', width: '100px', height: '100px' })), state('final', way({ backgroundColor: 'ruddy', width: '200px', height: '200px' })), transition('initial=>final', animate('1500ms')), transition('final=>initial', animate('1000ms')) ]), ] Hither nosotros have defined a trigger changeDivSize and two state functions inside the trigger. The element will be dark-green in the "initial" state and will be scarlet with an increased width and superlative in the "concluding" country.
We have divers transitions for the state alter. Transition from "initial" state to "terminal" will take 1500ms and from "final" state to "initial" will take 1000ms.
To change the land of our element we will define a function in the grade 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 post-obit code:
<h3>Change the div size</h3> <button (click)="changeState()">Modify Size</push button> <br /> <div [@changeDivSize]=currentState></div> <br /> We have defined a push which will invoke the changeState office when clicked. We have defined a <div> element and applied the animation trigger changeDivSize to information technology. When we click on the button it will flip the state of the <div> chemical element and its size will change with a transition issue.
Before executing the application, we demand to include the reference to our Animationdemo component inside the app.component.html file.
Open app.component.html file. Y'all tin see nosotros have some default HTML code in this file. Delete all the code and put the selector of our component as shown below:
<app-animationdemo></app-animationdemo> To execute the code run the ng serve command in the VS code terminal window. After running this command, information technology will ask to open up http://localhost:4200 in the browser. Then, open any browser on your motorcar and navigate to this URL. You can see a webpage as shown below. Click on the push to see the animation.
Balloon effect animation
In the previous animation, the transition happened in 2 directions. In this section, nosotros will learn how to change the size from all directions. It volition be like to inflating and deflating a airship, hence the proper name airship effect animation.
Add the following trigger definition in the animation property:
trigger('balloonEffect', [ state('initial', manner({ backgroundColor: 'green', transform: 'scale(i)' })), state('last', style({ backgroundColor: 'red', transform: 'calibration(1.v)' })), transition('final=>initial', animate('1000ms')), transition('initial=>final', animate('1500ms')) ]), Here, instead of defining the width and height property, nosotros are using the transform property to modify the size from all directions. The transition will occur when the state of the element is inverse.
Add the following HTML code in the app.component.html file:
<h3>Balloon Effect</h3> <div (click)="changeState()" mode="width:100px;height:100px; border-radius: 100%; margin: 3rem; background-color: green" [@balloonEffect]=currentState> </div> Hither we have defined a div and applied the CSS style to brand it a circumvolve. Clicking on the div will invoke the changeState method to switch the element'southward state.
Open the browser to see the animation in activeness every bit shown beneath:
Fade In and Fade Out animation
Sometimes nosotros want to show blitheness while adding or removing an element on the DOM. We volition see how to breathing the addition and removal of an item to a list with a fade-in and fade-out effect.
Add the post-obit code within the AnimationdemoComponent class definition for calculation and removing the chemical element in a list:
listItem = []; list_order: number = 1; addItem() { var listitem = "ListItem " + this.list_order; this.list_order++; this.listItem.button(listitem); } removeItem() { this.listItem.length -= 1; } Add together the post-obit trigger definition in the blitheness property:
trigger('fadeInOut', [ state('void', style({ opacity: 0 })), transition('void <=> *', breathing(g)), ]), Hither nosotros have defined the trigger fadeInOut. When the element is added to the DOM it is a transition from void to wildcard (*) land. This is denoted using void =>; *. When the chemical 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 => * and * => void volition take 1000ms to consummate.
Add together the following HTML code in app.component.html file.
<h3>Fade-In and Fade-Out animation</h3> <button (click)="addItem()">Add Listing</button> <push button (click)="removeItem()">Remove List</button> <div mode="width:200px; margin-left: 20px"> <ul> <li *ngFor="let list of listItem" [@fadeInOut]> {{listing}} </li> </ul> </div> Here nosotros 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 beneath:
Enter and Leave blitheness
When calculation to the DOM, the element will enter the screen from the left. When deleting, the element will get out the screen from the right.
The transition from void => * and * => void is very mutual. 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', manner({ transform: 'translateX(0)' })), transition(':enter', [ fashion({ transform: 'translateX(-100%)' }), animate('0.5s 300ms ease-in') ]), transition(':exit', [ animate('0.3s ease-out', style({ transform: 'translateX(100%)' })) ]) ]) Hither we have defined the trigger EnterLeave. The ':enter' transition volition wait for 300ms then run for 0.5s with an ease-in effect. Whereas the ':go out transition will run for 0.3s with an ease-out upshot.
Add the following HTML code in the app.component.html file:
<h3>Enter and Leave animation</h3> <button (click)="addItem()">Add List</button> <button (click)="removeItem()">Remove List</push button> <div style="width:200px; margin-left: 20px"> <ul> <li *ngFor="let list of listItem" [@EnterLeave]="'flyIn'"> {{list}} </li> </ul> </div> Here nosotros are defining two buttons to add items to and remove them from the list. We are binding the EnterLeave trigger to the <li> chemical element that will show the enter and leave effect while being added and removed from the DOM.
Open up the browser to see the animation in activity every bit shown below:
Conclusion
In this article, nosotros've learned about Angular six animations. We explored the concept of animation states and transitions. Nosotros too saw a few animations in activity with the assist of a sample awarding.
Please get the source code from GitHub and play around to go a better understanding.
If y'all're preparing for interviews, read my article on C# Coding Questions For Technical Interviews.
Run into Too
- ASP.Cyberspace Cadre — Using Highcharts With Angular 5
- ASP.Cyberspace Cadre — CRUD Using Angular 5 And Entity Framework Core
- CRUD Operations With ASP.NET Cadre Using Athwart 5 And ADO.NET
- ASP.Internet Core — Getting Started With Blazor
- CRUD Using Blazor with MongoDB
- Creating An SPA Using Razor Pages With Blazor
Originally published at https://ankitsharmablogs.com/
Larn to code for costless. freeCodeCamp'due south open source curriculum has helped more than than 40,000 people get jobs as developers. Become started
Source: https://www.freecodecamp.org/news/how-to-use-animation-with-angular-6-675b19bc3496/
Posted by: kittrellkitn1938.blogspot.com

0 Response to "How Can I Animate A Div In Angular"
Post a Comment