Calculate the variance in days between two dates and assign the result to a separate field

I am working with two date fields, one labeled Commencement Date and the other as Expiration Date.

Objective:

  1. The goal is to calculate the difference in days between the selected commencement and expiration dates (expirationDate - commecementDate) and then populate this difference in another textbox named Term.

  2. Additionally, client-side validation messages should be displayed when necessary.

Challenges:

  1. When a user selects an expiration date first, followed by filling out the commencement date, the Term field does not show any value.
  2. Validation messages are not being displayed.

Please refer to my code on StackBlitz here.

Answer №1

validation process is functioning correctly;

give this a shot:

import { Component, VERSION } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  name = 'Angular ' + VERSION.major;
  public startDate: any;
  public endDate: any;
  public daysDifference: any;

  formGroup: FormGroup = new FormGroup({
    start: new FormControl('', Validators.required),
    end: new FormControl('', Validators.required),
    term: new FormControl(''),
  });

  startEvent(event: any) {
    let date = event.target.value;
    this.startDate = new Date(date);
    this.verify();
  }

  endEvent(event: any) {
    let date = event.target.value;
    this.endDate = new Date(date);
    this.verify();
  }

  verify() {
    if (this.startDate && this.endDate) {
      var time =
        this.endDate.getTime() - this.startDate.getTime();
      var days = time / (1000 * 3600 * 24); //Difference in Days

      if (days && days >= 0) {
        this.daysDifference = days;
      } else {
        this.daysDifference = null;
      }
    }
  }

  saveData(value: any): void {
    console.log(value);
  }

  cancelAction(): void {
    console.log('cancel');
  }
}

consider managing validation through reactiveForm itself (abstractControl)

explore the use of observables as well, they have simple operators that can streamline code

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

Different categories of "areas" found in TypeScript within Visual Studio 2013

In C#, we often use "regions," but unfortunately that feature is missing in TypeScript. Is there a way to group code sections in TypeScript? I came across this article on Stack Overflow discussing the absence of regions in TypeScript. I'm curious if ...

React TypeScript throws an error when a Socket.IO object is passed to a child component and appears as undefined

Currently, I'm developing a simple chat application as part of my university course. The code below represents a work-in-progress page for this project. While I am able to get the socket from the server and use it in the main component without any is ...

What are the steps to switch from a C-optimized version to a purely Python module for a standard library module like datetime in Python?

There are some standard library modules (like datetime, decimal, io) that have both C and pure Python implementations. You can refer to PEP 399 -- Pure Python/C Accelerator Module Compatibility Requirements for more information. Disabling the C accelerate ...

Uploading images using the power of Angular and Node.js

I have been struggling with a persistent issue for quite some time now, and I have not been able to find a solution anywhere. My goal is to allow users to update their avatars on their profiles. However, every time I attempt to pass the file to my node ser ...

Issues have been reported regarding the paramMap item consistently returning null when working with Angular 8 routing

I am encountering an issue with Angular 8 where I am trying to fetch some parameters or data from the route but consistently getting empty values. The component resides within a lazy-loaded module called 'message'. app-routing.module.ts: ... { ...

Master the Art of Crafting Unique URLs

I am developing a web page that requires me to call two queries, each requiring an ID. However, I'm unsure of the best way to pass these IDs in the URL. For instance, one query is for books and the other is for authors. Currently, I have considered tw ...

Explore the route parameter in Angular 2

Trying to transfer a variable between two components using route parameters? In the first component, an id is sent using this function: sendId(id : string) : void { this.router.navigate(['/component2', id]); } The routing module setup inclu ...

Using Two Unique Typeface Options in Material UI for ReactJS

Currently, in my React App, I am utilizing the Material UI library with Typescript instead of regular Javascript. I've encountered a small hurdle that I can't seem to overcome. The two typefaces I want to incorporate into my app are: Circular-S ...

Display a list of records retrieved from a Firebase query using ngFor to iterate through each instance

I'm currently using firebase and angular to work on a billing list project. The list contains data showing information for a specific month, you can refer to the imagehttps://i.stack.imgur.com/ZR4BE.png While querying the list was smooth, I encounte ...

In order to conceal the div tag once the animation concludes, I seek to implement React

I'm currently using the framer-motion library to add animation effects to my web page. I have a specific requirement where I want to hide a div tag used for animations once the animation is complete. Currently, after the animation finishes, the div t ...

Advantages and Disadvantages of Implementing Ajax for Form Validation

Exploring the benefits of validating forms with Ajax, I find it to be a valuable tool in preventing code redundancy. However, before making the switch, I am curious about any potential drawbacks compared to traditional JavaScript validation. While I have c ...

TypeORM's one-to-many relationship alters the primary entity once the relationship has been established

When working on my side project, I decided to implement a friend request system using NestJS + TypeORM for the backend. However, I encountered a peculiar issue where every time I tried to associate a Friend entity with a specific user, the target field of ...

MatTooltip component in Angular Material UI is malfunctioning

In my angular component within a hybrid application, I have incorporated the mattooltip directive with links. However, I am facing an issue where the tooltip position is not accurate when hovering over the first link. Sometimes, the tooltip appears empty o ...

Is there a way to simultaneously filter the mat table data source and its related asynchronous properties?

Scenario: My current setup consists of angular version 9.1.7, angular-material version 9.2.3, macOS version 10.14.6, and ngrx libraries (store, data, entity) version 9.1.2 Description: I currently have a functional material table with a MatTableDataSourc ...

Encountering a "subscribe is not a function" error while attempting to utilize a JSON file in Angular 2

My attempt to import a JSON file into my service is resulting in the following error: Error: Uncaught (in promise): TypeError: this._qs.getBasicInfo(...).subscribe is not a function(…) The current state of my service file is as follows @Injectable() ...

How can I exclude the last parameter from a function type in Typescript?

If I have a function type like this: type FunctionType = (a: number, b: string, c: boolean) => void How can I create a new type with the last parameter removed? type NewFunctionType = OmitLastParameter<FunctionType> Desired type for NewFunctionT ...

The ASP .Net Core 3.1 Angular template is malfunctioning

https://i.sstatic.net/T3hFx.pngAfter creating a new Web Project using the .Net Core with Angular template in Visual Studio 2019, I encountered an error when trying to build the solution. The error message stated: An unhandled exception occurred while proce ...

Issue with Material UI grid not rendering properly in TypeScript environment

I've been trying to replicate a grid from material-ui using React and Typescript. You can see a live demo here. I modified the example to work with Typescript, so my demo.tsx file looks like this: Code goes here... If you check out the live demo, y ...

Determining the argument data type when calling the function

const func = <T>( obj: T, attr: keyof T, arr: T[typeof attr][], ) => { } const obj = {foo: 1, bar: true}; func(obj, 'foo', [1]); func(obj, 'bar', [1]); // shouln't be ok func(obj, 'foo', [true]); // shoul ...

Encountering an issue in Angular where data.slice is not functioning properly, resorting to using parseInt to convert strings into Date

Looking to convert the data retrieved from the database into numbers and dates with ease. One set of data is in milliseconds while the other is in timestamps. https://i.stack.imgur.com/HdM0D.png The goal is to transform both types into numbers first, the ...