"Calculating the time difference between a specified time and the current time using Typescript can be achieved by

Incorporating Angular 7, my goal is to exhibit elements in the component HTML only if a certain condition is met: namely, if the provided time is ahead of the current time.

After several attempts, I came up with the following logic:

 checkTimeDifference(time, date)
{
     const currentDate = new Date()
     const slotDate = new Date(`${date} ${time}`);

     const difference = Math.abs(Math.abs(currentDate.getTime() - slotDate.getTime()) / 3600000)

    // If the difference is not negative
   if(difference) {
     return false;
  } 
    else {
     return true;
   }
 }

For implementing this in HTML:

<span *ngIf="checkTimeDifference(result.endtime, result.date)"> opened </span>

Update:

The elements are being showcased using *ngFor loop, thus calling getTimeDiff in ngOnInit() is not feasible.

<div *ngFor="let result of results">
    <span *ngIf="checkTimeDifference(result.endtime, result.date)"> opened </span>
</div>

However, an error is encountered stating:

ViewAppointmentsComponent.html:30 ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'null: 6.0732225'. Current value: 'null: 6.0732252777777775'.

Answer №1

Encountering a lifecycle error in Angular? It could be because the value has already been checked by Angular, but you're trying to update it unnecessarily.

If you insert a console log within your function, you'll notice that it's being called frequently. This is due to functions bound to directives being triggered with every user interaction.

Each time the function is called, a new date value (+1 ms) is fetched. To prevent this behavior, initialize your date value during component creation and compare against it. You can update it later if needed, but avoid doing so directly within the function.

constructor(private now = new Date()) {}

getTimeDiff(time, date)
{
     const slotDate = new Date(`${date} ${time}`);  // assuming time = '10:30:00' and date = '2018-11-14' 

     const diff = Math.abs(Math.abs(this.now.getTime() - slotDate.getTime()) /  3600000)

    // check if difference is not negative
   if(diff) {
     return false;
  } 
    else {
     return true;
   }
 }

EDIT

To prevent multiple calls of your function, consider using a variable that updates upon change:

this.timeDiff: boolean;

ngDoCheck() {
  this.timeDiff(this.result.endtime, this.result.date);
}

getTimeDiff(time, date)
{
     const slotDate = new Date(`${date} ${time}`);  // assuming time = '10:30:00' and date = '2018-11-14' 

     const diff = Math.abs(Math.abs(this.now.getTime() - slotDate.getTime()) /  3600000)

    // check if difference is not negative
   if(diff) {
     this.timeDiff = false;
  } 
    else {
     this.timeDiff =  true;
   }
 }

In your HTML:

<span *ngIf="timeDiff"> open </span>

ngDoCheck serves as a lifecycle hook (similar to ngOnInit) and is used for detecting changes that are not tracked by Angular.

Answer №2

Angular performs change detection and if it detects that the values passed to a child component have changed, Angular will throw an

ExpressionChangedAfterItHasBeenCheckedError
.

It is recommended to store the information in a variable rather than calling the same function on every change detection cycle.

different = false;  //<-- stores the difference state.

getTimeDiff(time, date)
{

     const currentDate = new Date()
     const slotDate = new Date(`${date} ${time}`);  // assuming time = '10:30:00' and date = '2018-11-14' 

     const diff = Math.abs(Math.abs(currentDate.getTime() - slotDate.getTime()) /  3600000)

    // if diff is not negative
   if(diff) {
     this.different = false  //<-- set to false.
  } 
    else {
     this.different  = true  //<-- set to true.
   }
 }

html

<span *ngIf="different"> open </span>

Note : Remember to call getTimeDiff function at the appropriate place like ngOnInit if you want it to run only once.

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

Generating Typescript definition files from JavaScript files with module.exports assignment

I'm currently working on creating a custom TypeScript definition file for format-duration: module.exports = (ms) => { let { days, hours, minutes, seconds } = parseMs(ms) seconds = addZero(seconds) if (days) return `${days}:${addZero(hours)}: ...

How to Create a Flexible Angular Array Input Component

I have been working on developing reusable form input components using Angular's reactive forms. However, I am currently encountering challenges with my FormArray input component. To overcome some issues, I had to resort to using double-type casting ...

Executing a service call within an Angular 2 structural directive

I've developed a custom structural directive to verify a user's permissions. The permissions are retrieved from the backend and stored in the service itself. The directive utilizes dependency injection to access the service and determine if a spe ...

What is the method for inserting two dashes within a number?

For the output, I am looking to showcase a number in the following format => 979-9638403-03. At present, the number appears like this => 979963840303. portfolio.ts export class Portfolio { ... DEPO: number; /* DEPO */ const ...

What are some recommended methods for sending payload while saving form data with a Reference field?

I'm working on a form that includes a Country Field in a dropdown menu. <mat-select> @for(country of control.countries; track choice){ <mat-option [value]="country.id">{{ country.name }}</mat-option> } </mat-sel ...

Issue encountered in Angular installation of Jest: unable to read property 'matches' as it is undefined

Need help with using jset in my angular project. When attempting to install with the command: npm install jest --save-dev An error is encountered: npm ERR! Cannot read property 'matches' of undefined Important to note that before installing j ...

What is the process for incorporating external JS files into an Angular 6 project's angular.json configuration?

I am encountering an issue with a sidebar menu script file located in the assets folder that I am including in my index.html file. The problem occurs when I navigate from the initial route / to the home/dashboard child route – the sidebar show/hidden but ...

Filtering rows in angular based on the current data's id

currData = { id: "iStyle1", status: "PENDING" }; data = [ { id: "splitStyle1", rows: [ { id: "1cUMlNRSapc5T", row: 2, sequence: 2, status: ...

Sorting an array of numbers in TypeScript using the array sort function

Looking to organize an array based on ID, comparing it with another array of numbers var items:[] = [{ item:{id:1},item:{id:2},item:{id:3},item:{id:4} }] var sorted:[] = [1,3,2,4]; Output: var items:[] = [{ item:{id:1},item:{id:3},item: ...

Display various items from a predefined list using Angular's *ngFor directive

Within my Angular project, I am managing a list of reports. This list is structured as an array with a base class to accommodate different types of reports. Even though the list is defined as type: ReturnReport, the individual items can vary between type: ...

The integration of ngx-translate with an HTTP interceptor is currently experiencing difficulties

Using ngxtranslate for application translation has been seamless so far. However, I am facing an issue with the HttpInterceptor. This interceptor attempts to retrieve data from local storage at the start and displays a dialog prompting you to either load t ...

Using Angular to embed an external PDF link into an iframe

Looking for some assistance, I'm attempting to embed an external PDF link into an <iframe> using my Angular-App: <embed [src]="downloadurl" style="width: 100%; height: 550px;" /> Unfortunately, I encountered this erro ...

Preventing JavaScript Compilation for a Specific Folder using tsconfig: A Step-by-Step Guide

To create my own npx package, I'm currently working on converting my .ts files into .js. The purpose of the application is to generate TypeScript templates for users based on their selected options. In this app, there's a CLI called 'index.t ...

What values are typically used in the "types" field of a package.json file?

As a newcomer in the realms of JS/TS, I am delving into creating an NPM package using TypeScript for educational purposes. To prepare the artifacts for registry upload, it's necessary to compile the TS files into JS files using the tsc command. Here i ...

Encountering an issue with Next.js, Typescript, and mongoose when attempting to use `let cached = global.mongoose

I attempted to create a cached mongoose connection for my Next.js + Typescript application, but the code I used was: let cached = global.mongoose; if (!cached) { cached = global.mongoose = { conn: null, promise: null }; } The use of global.mongoose res ...

Challenge encountered with asynchronous angular queries

Dealing with asynchronous calls in Angular can be tricky. One common issue is getting an array as undefined due to the asynchronous nature of the calls. How can this be solved? private fetchData(id){ var array = []; this.httpClient.get('someUrl ...

Obtain the object literal string with additional decorative strings surrounding it

In my current Typescript code, I have an object literal structured like this: const MyNamesStrings = { a: { b: "hello", c: "bye" } d: { e: "qwerty" } } However, I am looking for a way to wrap these strings with add ...

Having trouble pushing data to a GraphQL database from my Next.js application

I am currently working on developing a Reddit-like platform. To simplify the process, I have integrated SQL with graphQL using Stepzen for endpoints. Below is the code snippet of my Post Box component for the site, which includes graphQL mutations.ts and q ...

How can I integrate a timer into an Angular carousel feature?

I have put together a carousel based on a tutorial I found on a website. Check out the HTML code for my carousel below: <div class="row carousel" (mouseover)="mouseCheck()"> <!-- For the prev control button ...

Using TypeScript to specify precise types for ReactWrapper within the Enzyme library

During my testing process of custom components with jest and enzyme using typescript, I have been creating tests like this: const wrapper = mount(<MyCustomComponent/>); expect(wrapper).toMatchSnapshot(); As mount returns a type of ReactWrapper, I h ...