A guide on setting up a countdown timer in Angular 4 for a daily recurring event with the help of Rxjs Observable and the Async Pipe

I'm currently working on developing a countdown timer for a daily recurring event using Angular 4, RxJS Observables, and the Async Pipe feature. Let's take a look at my component implementation:

interface Time {
  hours: number;
  minutes: number;
  seconds: number;
}
@Component({
  selector: 'app-header-area',
  templateUrl: './header-area.component.html',
  styleUrls: [ './header-area.component.scss' ]
})
export class HeaderAreaComponent {
  @Input() language: LanguageState;
  @Input() menu: MenuState;

  remaining: Time;
  hoursLeft: number;
  minutesLeft: number;
  secondsLeft: number;

  timeLeft(date) {
    const utc_hours = date.getUTCHours();
    const utc_minutes = date.getUTCMinutes();
    const utc_seconds = date.getUTCSeconds();
    const end_hour = 20;
    const difference_hours = (utc_hours <= end_hour) ? (end_hour - utc_hours) : (24 + end_hour) - utc_hours;
    const difference_minutes = 60 - (utc_minutes % 60) - 1;;
    const difference_seconds = 60 - (utc_seconds % 60) - 1;;
    return <Time>{
      hours: difference_hours,
      minutes: difference_minutes,
      seconds: difference_seconds,   
    }
  }

  constructor() {
    timer(0, 1000).subscribe(() => {
      const time = this.timeLeft(new Date());
      const { hours, minutes, seconds } = time;
      this.hoursLeft = hours;
      this.minutesLeft = minutes;
      this.secondsLeft = seconds;
    });

  }

}

This is how I've set up my template:

<span class="auctions-text">Auctions close in <b>{{ hoursLeft }} hours {{ minutesLeft }}m {{ secondsLeft }}s</b></span>

My main query revolves around utilizing RXJS timer along with other operators to generate an Observable that can be seamlessly integrated with an async pipe within my template setup. Can anyone provide guidance on this?

Answer №1

Creating a basic countdown timer using seconds,

const endHours = 20
const endSeconds = endHours * 60 * 60;
const countdown$ = Observable.timer(0, 1000)
  .map(x => endSeconds - x)
  .takeWhile(x => x > 0);

const hoursLeft$ = countdown$.map(x => calcHoursFromSecondsRemaining(x));
const minsLeft$ = countdown$.map(x => calcMinsFromSecondsRemaining(x));
const secsLeft$ = countdown$.map(x => calcSecondsFromSecondsRemaining(x));

<span>{{ hoursLeft$ | async }}</span>
<span>{{ minsLeft$ | async }}</span>
<span>{{ secsLeft$ | async }}</span>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Effortless JSON parsing with Angular 2 Http GET request

After sending an HTTP get request to my server API, I am attempting to parse the JSON object that is returned. Below is the code snippet for the Http call: getPayoutReport(param1, param2, param3) { //perform necessary actions //set up a requestUr ...

Adjust the element's height as you scroll

I am currently experimenting with a method to dynamically increase the height of an element based on user scrolling behavior. Despite trying multiple approaches, I have encountered challenges in getting it to work effectively. The concept is as follows: ...

The CSS selectors wrapped in jQuery vary between Chrome and Internet Explorer 11

When utilizing a jquery wrapped css selector such as $($("#selector").find('input[type="textarea"])'), I am able to input values into the textarea in Chrome using $($("#selector").find('input[type="textarea"]).val(someValue)') but encou ...

Achieving CSS Buttons That Change to Green When Clicked and STAY Green

I've been tasked with working on a front-end project for a website that involves buttons changing color when clicked and staying that color. Here is the CSS <style> code I have written for these specific buttons: .button { background-color ...

Get the characters from a URL following a specific character until another specific character

Having some difficulty using JavaScript regex to extract a specific part of a URL while excluding characters that come after it. Here is my current progress: URL: With the code snippet url.match(/\/[^\/]+$/)[0], I am able to successfully extrac ...

Leveraging the OpenLayers Map functionality within an Angular service

I am curious to learn if there is a way to utilize a service in Angular for creating an OpenLayers map and then passing that service to other components to update the map based on interactions within those components. I have outlined my approach below. Des ...

Implementing a callback function following the completion of file reading in Phonegap

I have been facing this issue for quite some time now and I need assistance in finding a solution: When it comes to developing an android app, I rely on the phonegap framework. There is an async function called readFromFile() that reads a json file store ...

How can I display a popup window within an iframe on a separate full page?

I am facing an issue while creating an HTML table using AngularJS with a popup. The problem is that I want the popup window, which shows a graph, to open up on the entire page instead of in a specific div. My desired output should look like this: https://i ...

Revise regular expression for verifying addresses

In my angular app, I have created a regular expression for validating postal addresses. const regx = '\\b([p]*(ost)*\\.*\\s*[o|0]*(ffice)*\\.*\\s*b[o|0]x)\\b' I specifically want this ...

Trigger javascript function with a button click

Is there a way to trigger a JavaScript function from an HTML button that is not functioning properly? REVISED To see the issue in action, please visit this jsfiddle link: http://jsfiddle.net/winresh24/Sq7hg/341/ <button onclick="myFunction()">Try i ...

Automate the compilation of Typescript project references by creating a solution that allows for passing unique options to each

When compiling or building a project with references programmatically, I make use of the ts.createSolutionBuilder API. The challenge I face is that in my specific scenario, I do not have individual tsconfig.json files stored on the filesystem for each pac ...

Can someone show me how to implement arrow functions within React components?

I am facing an issue while working on a node and react project. Whenever I use an arrow function, it shows an error stating that the function is not defined. Despite trying various tutorials and guides, I am unable to resolve this issue. Below is the snipp ...

What is the best way to organize the table by date when not all dates are filled in?

**Issue with React-Table Sorting:** I'm encountering an issue with my React-Table implementation. I am using version 7 of the plugin. { Header: 'DATE', accessor: 'DATE', sortType: (rowA, rowB) => { ...

Samsung browser encounters an international error

After developing my web application using Angular2 Rc1, I noticed that it functions perfectly on Safari, Firefox, and Chrome browsers. However, when trying to access the application on my Galaxy S6 using the default browser, an error pops up: To address ...

Discover the steps to capture the ajax initiation and completion events

In my application, I have numerous ajax requests. To display a loading symbol while these requests are in progress, I am utilizing jquery ajaxStart and ajaxStop methods. However, for some reason, they seem to not be functioning as expected. Despite searc ...

Setting a value in Ionic 3 HTML template

Attempting to assign a value in an Ionic 3 template from the ts file while also adding css properties but encountered an issue. PROBLEM Error: Uncaught (in promise): Error: No value accessor for form control with name: 'image' Error: No va ...

Ways to show a div when a dropdown option is selected

Currently, I am in the process of designing a form that includes a dropdown menu. Once the user selects a particular option from the list, such as: Software developer a new section will be displayed, showing two additional options: App Developer ...

Display an empty string when a value is NULL using jQuery's .append() function

To set an HTML value using the .append() function, I need to include AJAX data values. If the data set contains a null value, it will show as 'null' in the UI. I want to remove that 'null' and display it as blank. However, I can't ...

List of duplicated BLE devices detected in network scanning

Greetings! I am currently working on an Ionic project named BLE Scanner. After facing some challenges, I finally managed to connect to the devices. Below is the code snippet that I discovered online: home.ts (please ignore the DetailPage) import { Compon ...

What is causing the consistent occurrences of receiving false in Angular?

findUser(id:number):boolean{ var bool :boolean =false this.companyService.query().subscribe((result)=>{ for (let i = 0; i < result.json.length; i++) { try { if( id == result.json[i].user.id) ...