Show the current time using Moment.js

I am currently working on developing a clock component that displays the current time in real-time.

Issue: The initial time is correctly displayed when the page loads (HH:mm A), but the clock does not update dynamically.

clock.component.ts :

import {
    ChangeDetectionStrategy,
    Component,
    OnInit
} from "@angular/core";
import { Observable, interval } from "rxjs";
import { map, distinctUntilChanged } from "rxjs/operators";
import * as moment from "moment";

@Component({
    selector: "app-clock",
    templateUrl: "./clock.component.html",
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class ClockComponent implements OnInit {

    pageLoaded: moment.Moment;
    time: Observable<string>;

    constructor() {}

    ngOnInit() {
        this.pageLoaded = moment(new Date());

        this.time = interval(1000).pipe(
            map(() => this.pageLoaded.format("HH:mm A")),
            distinctUntilChanged()
        );
    }
}

clock.component.html :

<div>{{ time | async }}</div>

Answer №1

If I were in your shoes, I would recommend using @types/moment to simplify things (optional).

Now, why is the clock not updating?

The reason is that you initialized the clock value only once when the page loaded, and it doesn't get updated thereafter. Essentially, this.time retains the initialized value instead of the current one. Here is an updated version of your component:

import {
    ChangeDetectionStrategy,
    Component,
    OnInit
} from "@angular/core";
import { Observable, interval } from "rxjs";
import { map, distinctUntilChanged } from "rxjs/operators";
import moment, { Moment } from "moment"; // importing @types/moment

@Component({
    selector: "app-clock",
    templateUrl: "./clock.component.html",
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class ClockComponent implements OnInit {

    pageLoaded: Moment;
    time: Observable<string>;

    constructor() {}

    ngOnInit() {
    this.time = interval(1000*60).pipe(
      map(() => {
        this.pageLoaded = moment(new Date());
        return this.pageLoaded.format("HH:mm A");
      })
    );
  }
}

Your view remains unchanged.

You can see a StackBlitz example by following this link: https://stackblitz.com/edit/angular-moment-rxjs

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

Tips for saving data obtained from an ajax call

My jquery ajax function has a callback that creates an array from retrieved json data. Here's an example: success: function (response) { callback(response); }, The callback function, in this case createQuestionsArray(), populates ...

Difficulty with Pomodoro clock's canvas ring function not working as expected

Hey everyone, good evening. I've been struggling with a particular section of code for quite some time now and could really use some help. When you check out the constructor at this.drawArc and then look into the prototype, I've printed a couple ...

Do I need to include success as a parameter in my Ajax call even if my function does not return any values?

When an image is clicked, I trigger an ajax call. The image includes an href tag that opens a different page in a new tab upon click. The purpose of this ajax call is to record the user's clicks on the image for telemetry purposes in a database table. ...

What is the best way to choose the next adjacent element using a CSS selector with Python Selenium?

The structure of the DOM is as shown below: <ul> <li> <a href="#" role="button" class="js-pagination link" data-page="1">1</a> </li> <li> <a href="#" role="button" class="js-pagination link active" data ...

Hey there! I'm experiencing an issue with the jquery function $(this).childen().val()

Here is my HTML and JS/jQuery code: (function($) { $('.list-group li').click(function(){ console.log("push li"); console.log($(this).attr('class')); console.log($(this).children('.hidden_input&ap ...

Transmit information using $broadcast when a button is clicked, and retrieve that information using $scope.$on

I am trying to create a function that will broadcast data from the server upon button click, and then navigate to a new route using $state.go('new-route'). In the controller of this new state, I want to retrieve the transmitted data. However, whe ...

What is the process for accessing jQuery methods in Node.js?

When working on the client side, using Object.keys($.fn) (or Object.keys(jQuery.fn)) is a simple way to retrieve jQuery functions as an array. But how can I achieve the same result of getting this array with the jquery package from npm? I attempted: re ...

What is the best way to restrict the input options for a String field within a TextField component in Material-UI?

When working with Material-UI, how can we set a maximum length restriction for a text field? Below you will find an example of the TextField component: <TextField id="name" label="Name" type="string" //maxLengt ...

Refresh the div element's HTML and content using AJAX

I am interested in implementing a feature similar to the StackExchange link found on the top left of the Stack Overflow site. From what I gather, when the stack exchange link is clicked, the following actions take place: The hidden div container becom ...

The selected plugin appears to be incompatible with mobile browsers

My project involves implementing the Chosen plugin for a select field, allowing users to type-search through lengthy lists. It functions perfectly on desktop but is disabled on both Apple and Android phones, reverting to the default user interface for sele ...

The functionality of the ajax hash navigation feature seems to be malfunctioning

I've been trying to use hashes for my navigation, but everytime the page loads, my script resets the initial hash to #home. It doesn't matter what hash I add in the URL: Here is the script that runs to check if the hash exists and what content t ...

In a React TypeScript application, prevent users from clicking on buttons that represent the same number of answers in a multiple choice question

I'm currently developing a multiple choice component with various properties like the number of options, number of answers, and a callback function to capture user-selected data. Additionally, this component should display a checkmark when a button is ...

The CORS Policy has prevented Angular from accessing the header, as the request header field for authentication is restricted

After reviewing a multitude of similar questions regarding CORS and headers, I have attempted various solutions but I am still encountering this error specifically in Google Chrome. Access to XMLHttpRequest at 'https://service.domain.com/clientlist&ap ...

What is the best way to display all HTML content using PHP?

I have an HTML page with a multitude of CSS and JavaScript tags in its head section. My goal is to print them as they are on a PHP page. I've attempted using PHP echo file_get_contents("html_url"); and the fread function. The PHP page successfully loa ...

An error persists in PhpStorm inspection regarding the absence of AppComponent declaration in an Angular module

After creating a new Angular application, I am encountering the issue of getting the error message "X is not declared in any Angular module" on every component, including the automatically generated AppComponent. Despite having the latest version of the An ...

hide elements only when there is no string to display in Angular2/Typescript

As I experiment with my javascript/typescript code, I've encountered an issue where a string is displayed letter by letter perfectly fine. However, once the entire string is shown, the element containing it disappears and allows the bottom element to ...

Extracting the "defined" type from a TypeScript property during runtime

My current task Presently, I am iterating through the keys of an object and transferring their values to another object. interface From { [key: string]: string; } let from: From = { prop1: "foo", prop2: "23", }; interface To { [key: str ...

Tips for adjusting the minimum attribute within an input field with jQuery

In my form, I have an input field with arrows (up and down). Next to it, there are two buttons: + and -. When I click on the input field and then use the arrow, the system retrieves the value from a dropdown list, which works fine. However, when I use the ...

The HTML was generated without any styling properties assigned

After running my script on a galaxy tab, I encountered a strange issue. I created an HTML element (div) and attempted to access the style attribute, only to receive an error message indicating that style is null. Below is the code snippet: var newDiv = d ...

Delay the execution until all promises inside the for loop are resolved in Angular 7 using Typescript

I am currently working on a project using Angular 7. I have a function that contains a promise which saves the result in an array as shown below: appendImage(item){ this.imageCompress.compressFile(item, 50, 50).then( result => { this.compressedI ...