How to animate single item from ngFor loop of object items? Let's say we are looping list of users, and then we will perform some action in UI on specific user item. We want to start animation triggered by action, to display the user that something happened with that user item. And by the way we will include also list animation, every item from user object will be animated on page load (thank me)
Animate single item from ngFor loop
In this example we will be using material design, but i will not explain how to include it, more info about it you can find here
So let's start, first we will create user list, open app.components.ts and add object:
As you can see we are using functions to change the role and status:
setUserRole() and setUserStatus()
let's add them to app.component.ts
setUserRole(status,user){
// here we are making timeout to simulate request to backend
setTimeout(() => {
// change value
user.membership = status;
},300);
}
setUserStatus(status,user){
// here we are making timeout to simulate request to backend
setTimeout(() => {
// change value
user.status = status;
},300);
}
Ok, now let's add some animations. Create animations.ts and place it in root folder.
Here we have two animations, actionAnimation and listAnimation. ListAnimation will be triggered on page load and actionAnimation will be triggered on action change. So, let's add triggers to HTML. Open app.component.html and add it:
<div fxLayout="row>" [@listAnimation]="users.length">
<div
*ngFor="let user of users"
fxFlex="300px"
class="padding-10"[@actionAnimation]="user.state" >
...
Action animation have two states "orig" and "small" by default we will set all user to have state:'orig', we can do this on onInit() method in app.cmponents.ts:
Now, we will just change the state on action call, so in methods setUserStatus and setUserRole we will change the user status for that specific item. These two methods now will look like this:
setUserRole(status,user){
/*
NOTE: here is important to not update this.users because then we can see flickering, but to update user item passed in function and grabbed from ngFor loop
*/
// set animation state
user.state = 'small';
// here we are making timeout to simulate request to backend
setTimeout(() => {
// change value
user.membership = status;
// back to original state
user.state = 'orig';
},300);
}
setUserStatus(status,user){
// set animation state
user.state = 'small';
// here we are making timeout to simulate request to backend
setTimeout(() => {
// change value
user.status = status;
// back to original state
user.state = 'orig';
},300);
}
And that should be it, you can take a look at finished example. Please click on menu to change user role or status: