3

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?

TheUnreal
  • 23,434
  • 46
  • 157
  • 277

1 Answers1

8

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.

Joel Almeida
  • 7,939
  • 5
  • 25
  • 51
  • I think you'll have to wrap the `setTimeout()`'s callback with `NgZone.run()` or one of these options to update the view: http://stackoverflow.com/questions/34827334/triggering-angular2-change-detection-manually – martin May 20 '16 at 08:25
  • I've just tried it locally and it worked without forcing the change detection. – Joel Almeida May 20 '16 at 08:32
  • 2
    @Martin, `setTimeout()` is monkey-patched by Angular's zone. Since Joel is calling `setTimeout()` inside Angular code (hence inside Angular's zone), when the timeout fires, change detection will be called after the callback function runs, as desired (because of the monkey-patching). – Mark Rajcok May 20 '16 at 14:59