Learn how to calculate and showcase time discrepancies in minutes using Angular2

I am currently working on an Angular app that displays orders using the *ngFor directive. Each order has a datetime field indicating the date it was created. My goal is to implement a timer that shows how long a customer has been waiting for their order in minutes, by calculating the difference between the order creation time and the current time. I attempted to use the amDifference pipe, but it displayed the same output for all records. While it would be straightforward to do this for a single item, I am unsure how to achieve this within the *ngFor loop.

<mat-card class="order-card" *ngFor="let order of orders?.orders">
  <mat-card-subtitle>
    Customer Name: {{ order.customerName }}
  </mat-card-subtitle>

  <mat-card-subtitle>
    Table Number: {{ order.tableNumber }}
  </mat-card-subtitle>

  <mat-card-subtitle>
    Food: {{ order.food }}
  </mat-card-subtitle>

  <mat-card-subtitle>
    Drink: {{ order.drink }}
  </mat-card-subtitle>

  <mat-card-subtitle>
    Estimated Wait Time: {{ order.waitTime }} minutes
  </mat-card-subtitle>

  <mat-card-subtitle>
    Actual wait time: <!-- this is where I want to display dynamic time difference between now and order.time -->
  </mat-card-subtitle>
  <button mat-button class="delete-button" color="primary" (click)="deleteOrder(order.orderId)">Remove Order</button>
</mat-card>

Answer №1

Instead of relying on amDifference/custom pipes, I took a unique approach by precalculating the minute difference within the class itself. Take a look at my code below and feel free to provide any suggestions or feedback.

order.ts

export class Order {
mins:number;
    constructor(private id:number, private time:Date, private now:Date) {
        let diffInMilliSecs:number  = (this.now.getTime()-time.getTime()) ;

        let diffinMins: number = diffInMilliSecs / 1000/60;
        this.mins =Math.round(diffinMins);
    }
}

app.component.ts

import { Component} from '@angular/core';
import { Order } from './order';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent{
  title = 'Orders';
  dateNow=new Date();

  orders = [ new Order(1,new Date("13 Mar 2019 19:50:14 EDT"),this.dateNow),
  new Order(1,new Date("13 Mar 2019 20:15:20 EDT"),this.dateNow),
  new Order(1,new Date("13 Mar 2019 20:45:55 EDT"),this.dateNow),
  new Order(1,new Date("13 Mar 2019 20:15:02 EDT"),this.dateNow),
  new Order(1,new Date("13 Mar 2019 20:15:00 EDT"),this.dateNow)];

}

app.component.html

<h1>  {{title}} </h1>
<h3> Time Now: {{dateNow}}</h3>

<table>
  <tr><th> Order#</th> <th>Order time</th> <th>Wait time (in mins)</th></tr>
  <tr *ngFor="let order of orders">
    <td>{{order.id}}</td>
    <td>{{order.time | date:'medium'}}</td>
     <td>{{order.mins}}</td> 
  </tr>

</table>

https://i.sstatic.net/xOzDI.png

Answer №2

Give this a shot

{{ currentTime | timeDifference:  order.time : 'minutes'}} minutes

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

Is there a way to insert a value into the input field using JQuery or JavaScript?

After reading my previous post on posting values into an input box, a commenter suggested using JQuery or Javascript. For more code and information, please refer to the link provided above. <label>Date</label>:&nbsp&nbsp <input sty ...

Capturing the MulterError

While using Multer, I encountered an issue with returning a custom error if a file already exists. My current approach involves using "cb(new Error('Flyer already exists'));" within a callback function when the file is detected as existing. Howev ...

Tips for showcasing an uploaded image with ajax

I am looking to upload an image and display it without having to reload the page. I believe this can be achieved using Ajax form submission. However, I have tried some code but the Ajax form submit function does not seem to be working for me. Can someone p ...

Tips for identifying the most effective element locator in the DOM with Playwright

Currently, I am in the process of incorporating Playwright tests for a website that supports multiple locales. The majority of the page content is dynamically generated from CMS content (Contentful). I am hesitant about using hardcoded text locators like ...

acquiring environmental variables in TypeScript for node applications

I am struggling with accessing process.env variables in my TypeScript pages. It seems to be a scope issue, which doesn't make sense to me as a beginner in TypeScript. To get my environment variables, I use a YAML file and attach them to the running p ...

Utilize Nuxt.js context within a Vue plugin

I have a situation where I'm working with Nuxt.js and have two plugins set up. In order to gain access to the VueI18n instance from lang.js within validate.js, I am in need of some guidance. Is there anyone familiar with how this can be accomplished? ...

It appears that the ngRepeatWatch feature is causing a slowdown in Batarang

After reviewing the Batarang analysis of my AngularJS app, I have discovered the following: ngRepeatWatch | 64.2% | 136.0ms Surprisingly, this instruction takes up 10 times more time than the next reported instructions. Could this indicate that I am pot ...

Improving the Sum of Pairs solution on Codewars

Seeking assistance in optimizing a solution for a problem that has already been identified. However, the existing code is not efficient when dealing with large arrays - view the problem on codeWars : Sum of Pairs Below is the current code snippet: var s ...

JS receiving a reference to an undefined variable from Flask

I referenced this helpful post on Stack Overflow to transfer data from Flask to a JS file. Flask: @app.route('/') def home(): content = "Hello" return render_template('index.html', content=content) HTML <head> ...

I am facing an issue with my ngx-translator in Ionic4 as it is unable to retrieve the current language

I am having an issue with the ngx-translator package where I am unable to set the default language in my application. Here is the code snippet from my app.module.ts: import { TranslateModule, TranslateLoader } from '@ngx-translate/core'; import ...

How can I dynamically set the selected index in Nebular's nb-stepper using code?

Currently, I am testing out the nb-stepper component and wanted to configure the selectedIndex in my Angular component. However, when I try to apply two-way binding on [(selectedIndex)] and refresh my activities, the nb-step does not update to display the ...

Is it possible to adjust the size of a p5.js canvas within a bootstrap Div container?

I am attempting to incorporate a p5js canvas into a bootstrap grid structure. My goal is to have each div within the grid contain its own unique p5js canvas, which should adjust in size when the browser is resized. Below is my bootstrap grid setup, showca ...

A comprehensive tool for testing JavaScript, CSS, HTML, and jQuery code

Currently, I am working on an extension for Google Chrome that consists of multiple .js, .css, and .html files. My coding process involves using Notepad++ as my primary tool. However, I find myself needing to conduct testing at various stages of developm ...

Is it possible for me to utilize a validation function to display error messages within a specific span id tag?

document.getElementById("button1").addEventListener("click", mouseOver1); function mouseOver1(){ document.getElementById("button1").style.color = "red"; } document.getElementById("button2").addEventListener("click", mouseOver); function mous ...

Comparing Data Manipulation Techniques: Server Side vs Client Side Approaches in Reddit API Integration

As I delve into creating a simple Node/Express web application that fetches data from the Reddit API, performs some alterations on it, and intends to present this information using Charts.js on the client side, I find myself facing a dilemma due to my limi ...

Trouble encountered when trying to use an anchor link with the .slideUp jQuery function

Would you be able to assist me with understanding why my anchor links are not functioning correctly? I have 3 anchor links, for example: Google (not working) Yahoo (not working) Facebook (working) Any insights on why Google and Yahoo are not working? &l ...

Traversing through Object consisting of dual arrays within VueJS

Currently, I am working on a chat application built in VueJS and encountering an issue when attempting to display messages along with their respective timestamps. The challenge arises from the need to iterate through an object that contains two arrays: one ...

`Inability to remove item from array in Vue.js`

I've been struggling to understand why this feature isn't functioning as expected. I'm using sample code for reference, but it's not behaving the same way. When I click on the delete button, nothing happens even though it should remove ...

Errors encountered when using Mongoose and TypeScript for operations involving $addToSet, $push, and $pull

I am encountering an issue with a function that subscribes a "userId" to a threadId as shown below: suscribeToThread: async (threadId: IThread["_id"], userId: IUser["_id"]) => { return await threadModel.updateOne( { _id: t ...

Transferring Parameters to EJS Template in Node.js

Hey guys, I'm having an issue with rendering a MongoDB record in my .ejs file. Strangely, when I console.log the variable before the end of my route, I get the expected value. However, it becomes undefined in the .ejs file. Here is the code snippet: ...