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

Guide to implementing an enum in an Angular Component

Having a global state (or "mode") in my Angular Components is leading me to look for more efficient ways to code. Here is what I have tried: @Component({ .... }) export class AbcComponent implements OnInit { enum State { init, view, edit, cre ...

Illustrative demonstration of Vue with TypeScript

I am currently working on developing a HelloWorld application using Vue.js and TypeScript. index.html <script data-main="app.js" src="node_modules/requirejs/require.js"></script> <div id="app">{{text}}</div> app.ts import Vue f ...

Unusual increase in the Date() function hour on March 12, 2017

I encountered an issue where creating a new Date() object for March 12, 2017 with the hour set to 2am displays as 3am when using getHours(). The expected output should be 2am. Could there be an error in my code? I have highlighted the problematic section ...

Is it possible to multitask within a structural directive by performing two actions simultaneously?

I want to develop a custom structural directive with the following behavior: <p *myDirective="condition">This is some text</p> If condition is false, the <p> tag will not be displayed at all. If condition is true, the <p> tag wi ...

Discover more efficient methods for utilizing generics in hierarchical objects within typescript

How can I optimize the structure of an object that contains nested objects in Typescript to minimize type repetitions? type itemType = { [key: string]: { [key: string]: { [key: string]: { [key: string]: string } }; }; }; ...

Changing row colors based on property conditions in Angular 4

Hey there! I'm fairly new to Angular 4 and I've been working on creating a p-dataTable. My goal is to change the color of each row based on the quantity property of my object. Specifically, if the quantity is less than 10, I want the row to be di ...

Using routerLink for linking to multiple components

Below is the anchor tag provided: <a class="uppercase" routerLink="settings/pressure" routerLinkActive="text-success" (click)="closeModal()" > <div class="pad-btm"> PRESSURE </div> </a> I need to include another route ...

Navigating through pages in your IONIC 3 application: A guide to routing

I have been working on an Ionic 3 project and currently using NavController for page navigation. For example: this.navCtrl.push(DetailsPage); However, I now need to switch to Angular routing. I came across a similar query regarding Ionic 2 in this link. ...

Tips on avoiding updates to a defined object when a new object is filtered (created from the original object)

Is there a way to filter an array of objects based on their year without altering the original object? Whenever I apply a filter, it affects both the newly created object and the original one. However, I need the original object to remain unchanged so that ...

Implementing a click event on an image in an Angular 4 application

I'm facing an issue with adding a click event to an image within an Angular component. I have tried the following code: <img src="../../assets/add.svg" width="18" height="18" (click)="addItem()"> However, this approach does not seem to work as ...

Successive type label

Looking to create an object that can have either primitives or objects as properties? Avoid pitfalls like the following: const obj: DesiredType = { correctProp1: 'string', correctProp2: 123, correctProp3: true, wrongProp4: [1, 2, 3], pr ...

Forgot to include a semicolon in your code? If you attempted to parse SCSS using the regular CSS parser, give it another shot but this time with the

I am currently working on an Angular 14 project and one of my tasks involves changing the default font to our company's specific font. We are utilizing Angular material components and styles, so it is important for me to not only set the default font ...

Tips for troubleshooting the error message: "The relative import path "$fresh/dev.ts" is not prefaced with / or ./ or ../"

My editor is showing a TypeScript error for a Deno module I am working on. The import path "$fresh/dev.ts" should be prefixed with / or ./ or ../ I have an import_map.json file set up with the following content. { "imports": { "$fre ...

Having trouble calling a method from one component to another using its instance

Trying to call a method from one component to another is causing some issues. I have created an instance of the component and tried calling its method, but it doesn't seem to be working as expected. In the code snippet below, you can see that I am try ...

retrieving dynamic information from beyond the subscribe function

In order to implement canActivate for user routes, I need to first verify the validity of the access token. Below is the approach I am taking: export class AuthGuard implements CanActivate { data:Array<Object>; constructor(private base: BaseServ ...

Precise object mapping with Redux and Typescript

In my redux slice, I have defined a MyState interface with the following structure: interface MyState { key1: string, key2: boolean, key3: number, } There is an action named set which has this implementation: set: (state: MyState, action: PayloadAct ...

Angular BehaviorSubject is not refreshing quickly enough

After following a tutorial on creating full Angular + JWT Authentication, I encountered some issues when testing the project. In order to notify the AuthGuard that I am connected and can proceed to the next page upon logging in, I needed to send the API re ...

Issues encountered when retrieving data with ReactiveForms

My current project involves gathering data using ReactiveForms. Here is the structure of my setup: Initially, I create a modal to gather the necessary data: async present(){ const modal = await this.modalController.create({ component: dataComponent, cs ...

Updating and saving data in Ag-Grid with server communication

Is it possible to create a grid using Ag-Grid on Angular that fetches data from a local JSON file? And how can the edited row data be saved and sent to the server or back to the local JSON file? In summary, I would like to know how to save edited row data ...

Issues with compiling arise post downloading the latest Angular 2 quickstart files

My Angular 2 project was running smoothly on version 2.3, but I decided to upgrade to version 2.4. To do so, I downloaded the latest quickstart files from https://github.com/angular/quickstart After replacing my tsconfig.json, package.json, and systemjs.c ...