Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 add/change CSS class for a short time

Tags:

angular

I my angular 2 app, I have a label which shows the user current amount of points.

When the number of points is changed, I want to change the label's class for a short time, In order to make some kind of animation to let the user know something has changed.

<label class="label label-primary">
     {{userService.user.points}}
     </label>

In my service I get the user points using an observable and I can check if the number of points has changed using:

if (this.userData.points != data.user.points)

How I can change the label's class for a short time if the number of points has changed?

like image 926
TheUnreal Avatar asked Jul 02 '26 09:07

TheUnreal


1 Answers

You can do something like this:

<label class="label label-primary" [class.label-animate]="pointsChanged">
 {{userService.user.points}}
 </label>

And on your observable:

if (this.userData.points != data.user.points) {
  this.pointsChanged = true;
  window.setTimeout(() => this.pointsChanged = false, 200) // the time you want 
}

So basically, every time the points change, just keep a flag that toggles the class.

There are other solutions, I prefer this one because its simple.

like image 161
Joel Almeida Avatar answered Jul 05 '26 18:07

Joel Almeida



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!