Basic Angular animated counter for widgets and numbers with a start and end.
Working demo link below on stackblitz:
https://stackblitz.com/edit/angular-ivy-hzxd5h
This is an array of counters so many can be used once.
counters = [
{
limit: 10000000,
count: 2000,
speed: 200000,
},
{
limit: 50000,
count: 1000,
speed: 20000,
},
{
limit: 250000,
count: 256,
speed: 20000,
},
{
limit: 15000,
count: 1000,
speed: 10000,
},
];
Creating a method for each counter incremented based on start and final ratio. It will stop once counter hit the maximum limit of that particular counter.
updateCount = () => {
this.counters.forEach((counter) => {
const target = +counter.limit;
const count = +counter.count;
const speed = counter.speed;
const inc = target / speed;
if (count < target) {
counter.count = count + inc;
setTimeout(this.updateCount, 100);
} else {
counter.count = target;
}
});
};
Start this method with component ngOnInit()
ngOnInit(): void {
setTimeout(() => {
// delay animation for 3 seconds
this.updateCount();
}, 3000);
}
Use the counters variable in angular HTML. I am using number pipe for comma separated numbers.
<h3 class="count-number">{{ counters[0]['count'] | number }}+</h3>