How to Show a Countdown Timer in Angular using ngx-countdown

How to Show a Countdown Timer in Angular using ngx-countdown

Creating countdown timers in Angular applications has become increasingly important for modern web development. Whether you're building an e-commerce site with flash sales, event registration pages, or any application requiring time-sensitive features, implementing a reliable countdown timer is essential.

The ngx-countdown library provides a robust solution for Angular developers, offering extensive customization options and seamless integration with Angular's reactive architecture.

In this tutorial, we will learn how to add a countdown timer to your Angular project with ngx-countdown plugin step by step.:

What is ngx-countdown?

ngx-countdown is a powerful Angular library specifically designed for creating countdown timers. It offers real-time countdown functionality with multiple format options, making it perfect for various use cases including:

  • Product launch countdowns
  • Event registration deadlines
  • Flash sale timers
  • Session timeout warnings
  • Auction bidding timers

The library stands out for its lightweight nature, extensive customization capabilities, and excellent performance in Angular applications.

Installing ngx-countdown in Your Angular Project

Getting started with ngx-countdown requires a simple installation process. Follow these steps to add the library to your Angular project:

Step 1: To Install ngx-countdown, run the following command in your terminal:

npm install ngx-countdown --save

Step 2: Import the Module

Add the CountdownModule to your Angular module:

import { CountdownModule } from 'ngx-countdown';

@NgModule({
  imports: [
    CountdownModule
  ],
})
export class AppModule { }

For standalone components in Angular 20+, import it directly:

import { CountdownModule } from 'ngx-countdown';

@Component({
  standalone: true,
  imports: [CountdownModule],
  // component configuration
})

Basic Countdown Timer Implementation

Creating your first countdown timer with ngx-countdown involves minimal code. Here's a simple example:

Template Implementation

<countdown 
  [config]="countdownConfig"
  (event)="onCountdownEvent($event)">
</countdown>

Component Logic

import { Component } from '@angular/core';
import { CountdownConfig, CountdownEvent } from 'ngx-countdown';

@Component({
  selector: 'app-countdown',
  templateUrl: './countdown.component.html'
})
export class CountdownComponent {
  countdownConfig: CountdownConfig = {
    leftTime: 3600, // 1 hour in seconds
    format: 'HH:mm:ss'
  };

  onCountdownEvent(event: CountdownEvent) {
    if (event.action === 'done') {
      console.log('Countdown finished!');
    }
  }
}

This basic implementation creates a one-hour countdown timer displaying hours, minutes, and seconds.

Advanced Countdown Timer Configurations

ngx-countdown offers numerous configuration options to customize your timer's behavior and appearance:

Custom Format Options

countdownConfig: CountdownConfig = {
  leftTime: 86400, // 24 hours
  format: 'dd:HH:mm:ss',
  formatDate: ({ date, formatStr }) => {
    return formatStr
      .replace(/dd/g, String(Math.floor(date / 86400000)).padStart(2, '0'))
      .replace(/HH/g, String(Math.floor(date % 86400000 / 3600000)).padStart(2, '0'))
      .replace(/mm/g, String(Math.floor(date % 3600000 / 60000)).padStart(2, '0'))
      .replace(/ss/g, String(Math.floor(date % 60000 / 1000)).padStart(2, '0'));
  }
};

Styling and Customization

countdownConfig: CountdownConfig = {
  leftTime: 7200,
  format: 'HH:mm:ss',
  prettyText: (text) => {
    return text.split(':').map((v, i) => 
      `<span class="time-unit">${v}</span>`
    ).join('<span class="separator">:</span>');
  }
};

Handling Countdown Events

The ngx-countdown library provides several event types to handle different countdown states:

onCountdownEvent(event: CountdownEvent) {
  switch (event.action) {
    case 'start':
      console.log('Countdown started');
      break;
    case 'done':
      console.log('Countdown completed');
      this.handleCountdownComplete();
      break;
    case 'restart':
      console.log('Countdown restarted');
      break;
    case 'pause':
      console.log('Countdown paused');
      break;
    case 'resume':
      console.log('Countdown resumed');
      break;
  }
}

private handleCountdownComplete() {
  // Implement your completion logic
  alert('Time\'s up!');
}

Conclusion:

With ngx-countdown, adding a countdown timer to your Angular project is quick and easy. Whether you want to count down to a big event or a product launch, ngx-countdown has you covered. Give it a try and see how it can enhance the user experience on your site or app.

The ngx-countdown library provides Angular developers with a powerful, flexible solution for implementing countdown timers. Its extensive configuration options, event handling capabilities, and seamless integration make it an excellent choice for various time-sensitive applications.

Subscribe to our Newsletter

Stay up to date! Get all the latest posts delivered straight to your inbox.

If You Appreciate What We Do Here On TutsCoder, You Should Consider:

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Support Us

We are thankful for your never ending support.

Leave a Comment