Reputation: 2753
I have got a counter that is bound to view. Whenever the counter/model changes, the view updates as expected.
However, I would like the old value to go up and down. Am not looking for fading in/out between old and new values. I am looking for counter to go up/down, one figure at a time, till the new figure is reached.
Upvotes: 1
Views: 741
Reputation: 5357
You should create a component for that. That's the Angular way of doing it.
There are probably some third party libraries for that, but creating your own counter component is fairly easy. Here's one I created just now:
@Component({
selector: 'counter'
template: `<span>{{displayValue}}</span>`
})
export class Counter {
@Input() value: number;
private displayValue: number = 0;
private interval;
ngOnChanges(changes: {[propertyName: string]: SimpleChange}) {
clearInterval(this.interval);
let change = changes.value;
if (change) {
let target:number = parseInt(change.currentValue) || 0;
let step = target < this.displayValue ? -1 : 1;
this.interval = setInterval(() => {
if (this.displayValue !== target) {
this.displayValue += step;
}
else {
clearInterval(this.interval);
}
}, 100);
}
}
}
You can see a live demo of it here.
Upvotes: 1