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

The error message, "Property 'message' is not found on type 'ErrorRequestHandler<ParamsDictionary, any, any, ParsedQs, Record<string, any>>.ts(2339)", indicates that the requested property is not present in the specified type

Hello there! Recently, I implemented a custom error handling middleware in my Node.js TypeScript application. However, I encountered an issue where it is showing an error stating that 'message' does not exist on type 'ErrorRequestHandler&apo ...

Angular - Facing issues with CORS for every request made

Currently, I am developing an angular 12 application for my university with a java back-end. While testing Angular's http client, I encountered an issue where CORS is blocking my requests. const API_URL = 'http://localhost:9080' @Injectable ...

What are some methods to conceal an email address using Javascript?

let user = 'alex'; let domain = 'gmail.com'; let send = 'msg'; document.getElementById("email").href = "ma" + send + "ilto:" + user + "@" + domain; <a id="email"> <img src="imgs/pic.jpg"> </a> I have been w ...

Is utilizing React function components the most effective solution for this problem?

export default function loginUserUsing(loginType: string) { const [state, setState] = useState(loginType); function login() { // body of the login function } function oauth() { // body of the oauth function login(); ...

Experiencing difficulty in updating GitHub pages with React application

Looking for help updating my deployed active react app on GitHub pages with newer code, such as color changes and text updates. The updated code has been pushed to the main branch of my GitHub repo but the live GitHub page is not reflecting the changes. De ...

Real-time functionality in React component and Apollo Client is not functioning as expected

I am struggling to develop a user system as it is not working in real-time, causing confusion for me. To illustrate my problem and code, I have set up a sample Sandbox. Please note that this example does not include any validation features and is solely f ...

What is the appropriate way to utilize `render_template` from Flask within Angular?

I'm facing an issue where I need to implement different routes for various Angular Material tabs. I have attempted to directly call Flask from the template, as demonstrated below, but unfortunately, I am unable to invoke render_template from Angular. ...

Whenever I update the values in my input using the ngModel attribute, all of my arrays stored in an object also get updated

I am currently working with a table on the frontend. <table class="table table-hover"> <thead> <tr> <th> Account Entry Number </th> <th> ...

Assign the default value of a Vue prop to the options of its parent component

I have a child component that needs to accept a value given in the component's parent's $options object as a possible default value. In the background, the component should be able to receive its data through a prop or from a configuration. Howe ...

Utilizing namespacing in a JavaScript library can enhance organization and flexibility, providing

Creating a JavaScript library with multiple modules is my next project. Imagine the library is named Library, with modules One and Two. My goal is to allow end users to call the library in two ways: Library.One.somefunction(params) or somefunction(param ...

Modifying the color of a div based on a specified value using JavaScript

<div id="navigation"> Add your text here </div> <input type="text" id="newColor"><button onclick="modifyColor()">Update</button> <script> function modifyColor(){ var chosenColor = document.getElementB ...

Is it Possible to Achieve Callbacks From AJAX to PHP Despite the Inability to Serialize Closures?

Question How can I incorporate a PHP callback passed via AJAX, where the callback is executed by the page requested through AJAX? The Scenario Comments are submitted through AJAX with parameters serialized and encrypted for security. The issue arises wh ...

Tips for building a versatile fetch function that can be reused for various JSON formats within a React application

Using the fetch method in various components: fetch(url) .then(result => { if (!result.ok) { throw new Error("HTTP error " + result.status) } return result.json() }) .then(result => { ...

Tips for retaining behavioral subject data during page reload

I'm currently working on a component called properties.component.html that displays real estate properties. Whenever a user clicks on a particular property, I update a Behavior Subject to reflect this selected property. private property = new Behavio ...

Next.js encountering page not found error due to broken link URL

Currently, I am working on implementing a login system in next.js. In the login page, I have included a Link to the Register page using the Link href attribute. However, every time I click on that link, it displays a message saying "404 page not found." Al ...

Animation fails to initiate when the object enters the viewport

I attempted to inject some enchantment into my project by implementing code from a tutorial found on this CodePen. However, I encountered an issue where the code only functions properly within that specific CodePen environment. Even after copying the same ...

Material-UI is having trouble resolving the module '@material-ui/core/styles/createMuiTheme'

Although I have searched for similar issues on StackOverflow, none of the solutions seem to work for me. The errors I am encountering are unique and so are the fixes required, hence I decided to create a new post. The company conducting my test provided m ...

Utilizing the map() method for iterating through a nested property within a React component

Currently, my React setup involves rendering a prop named area which has the following structure: [{ "id": 1, "name": "Europe", "Countries": [{ "id": 1, "name": "Iceland", "Cities": [{ "id": 1, " ...

Creating an Editor for Input Text Field in HTML: A Step-by-Step Guide

In the vast landscape of JS libraries that can achieve this function, like Trumbowyg and more. However, prior to my rails project displaying that slim version, I need to ensure JavaScript is properly escaped! Therefore, I need to create an editor using o ...

Unable to delete element from the given array

I have been working on removing instances of 'store.state.location.locations' from my locationData array that should no longer be there, but for some reason, they are persisting in the array even though I am no longer passing those instances. ta ...