Automatically updating the date value in one matDatePicker field will impact the date in another matDatePicker field within a Reactive Form

I am struggling with dynamically updating the start date value in my reactive form, which requires setting the value of the start date field based on the statement date field value and a selected number of months.

<div [formGroup]="parameters">
<div class="mat-field">
    <mat-form-field color="primary">
        <mat-label>Statement Date</mat-label>
        <input id="statementDate" matInput [matDatepicker]="statementDatePicker"  formControlName="statementDate"  (dateChange)="datechanged()" >
        <mat-datepicker-toggle matSuffix [for]="statementDatePicker"></mat-datepicker-toggle>
        <mat-datepicker #statementDatePicker></mat-datepicker>
    </mat-form-field>
</div>
<div class="mat-field">
    <mat-form-field>
        <mat-label>Start Date</mat-label>
        <input id="startDate" matInput [matDatepicker]="startDatepicker" formControlName="startDate" readonly [disabled]="parameters.value.period!='other'">
        <mat-datepicker-toggle matSuffix [for]="startDatepicker"></mat-datepicker-toggle>
        <mat-datepicker #startDatepicker></mat-datepicker>
    </mat-form-field>
</div>
<div class="mat-field">

    <mat-form-field>
        <mat-label>Period</mat-label>
        <mat-select id="period" matInput formControlName="period" (selectionChange)="datechanged()">
            <mat-option value="12">12 Months</mat-option>
            <mat-option value="11">11 Months</mat-option>
            <mat-option value="10">10 Months</mat-option>
            <mat-option value="9">9 Months</mat-option>
            <mat-option value="8">8 Months</mat-option>
            <mat-option value="7">7 Months</mat-option>
            <mat-option value="6">6 Months</mat-option>
            <mat-option value="5">5 Months</mat-option>
            <mat-option value="4">4 Months</mat-option>
            <mat-option value="3">3 Months</mat-option>
            <mat-option value="2">2 Months</mat-option>
            <mat-option value="1">1 Month</mat-option>
            <mat-option value="other">other</mat-option>
        </mat-select>
    </mat-form-field>
</div>

ts file

 export class DatepickerMinMaxExample {
 parameters: FormGroup

  constructor(
    private fb: FormBuilder
  ) { }

  ngOnInit() {
   this.parameters = new FormGroup({
      'statementDate': new FormControl(null, Validators.required),
      'startDate': new FormControl(null, Validators.required),
      'period': new FormControl(null, Validators.required),
  });

  }
    
 public datechanged(){
    if(this.parameters.controls['statementDate'].value!=null&& this.parameters.controls['period'].value!=null&& this.parameters.controls['period'].value!='other'){
      let stmtDate=this.parameters.controls['statementDate'].value;
      let send_date=this.parameters.controls['statementDate'].value;
      console.log('statement date: '+ this.parameters.controls['statementDate'].value)
      let period=parseInt(this.parameters.controls['period'].value)
      let formattedDate : any;
   
      send_date.setMonth(send_date.getMonth()-period);
      send_date.setDate(send_date.getDate()+1);
      formattedDate=send_date.toISOString().slice(0,10);
      console.log('format date: '+ formattedDate)
      console.log('stment date after format date: '+ stmtDate)
      this.parameters.controls['startDate'].setValue(new Date(formattedDate))
    }

}
}

When dynamically updating the start date value, it affects the statement date matDatePicker and its value as well. https://i.sstatic.net/IGCDn.png

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

Visit Stackblitz for more details.

Any assistance in resolving this issue would be greatly appreciated. Thank you!

Answer №1

It appears that the variables stmtDate and send_date within your datechanged() function are reference types, pointing to

this.parameters.controls['statementDate'].value
. Changing either of these variables will result in a change to the date in your statementDatePicker.

To resolve this issue, performing a deep copy of these two fields using cloneDeep from Lodash should solve the problem.

      const _ = require("lodash");

      let stmtDate = _.cloneDeep(
        this.parameters.controls["statementDate"].value
      );
      let send_date = _.cloneDeep(
        this.parameters.controls["statementDate"].value
      );

(Note: I chose to use Lodash for deep copying instead of traditional methods like the spread operator, Object.assign(), and

JSON.parse(JSON.stringify(value))
as they do not copy functions, whereas cloneDeep from Lodash does. In your case, the send_date variable utilizes functions such as setMonth(), which necessitates a deep copy.)

I have created a working example on Stackblitz based on your code.

Answer №2

function updateDate(){
    if(this.data.fields['startDate'].value!=null&& this.data.fields['duration'].value!=null&& this.data.fields['duration'].value!='other'){
      this.data.fields['endDate'].setValue(new Date(this.data.fields['startDate'].value))
      let endDate=this.data.fields['endDate'].value
      let duration=parseInt(this.data.fields['duration'].value)
      let formattedEndDate : any;
   
      endDate.setMonth(endDate.getMonth()-duration);
      endDate.setDate(endDate.getDate()+1);
      formattedEndDate=endDate.toISOString().slice(0,10);
      this.data.fields['endDate'].setValue(new Date(formattedEndDate))
    }

}

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

Cannon-js: Experience dynamic body bouncing on the y axis as it reacts to force applied on the x and z axes

Currently, I am working on an FPS game where the player controller applies force based on keyboard inputs to a dynamic cannon body. The angular dampening is set to 1 on the player body. The PlayerController class takes both the player class (which extends ...

Navigating through the Angular Upgrade Roadmap: Transitioning from 5.0 to 6

As per the instructions found in this helpful guide, I executed rxjs-5-to-6-migrate -p src/tsconfig.app.json. However, an error is appearing. All previous steps were completed successfully without any issues. Any suggestions on how to resolve this? Please ...

Encountered an error while attempting to install the @typescript-eslint/eslint-plugin

After starting the installation process for eslint plugins, I encountered an issue with @typescript-eslint/eslint-plugin. The plugin requires installation using--legacy-peer-deps, but this approach may introduce potential bugs by accepting an incorrect an ...

Angular: utilizing two ngFors to target and update specific sections of the DOM

I'm facing a challenge and unsure if it's achievable in Angular. Below is a simple HTML code snippet: <div > <div *ngFor="let item of apiNames, let i = index" class="rescontainer"> <div class="resbox headline"> ...

All web browsers are supported by the HTML time input type for time formatting

Hello there, I'm currently dealing with an issue in my Angular / JHipster project. The problem lies with the input Forms, specifically the one with Type="TIME". While it displays correctly on my browser as (12:24), other browsers show it differently ...

App-Root in Angular 2 not loading properly in ExpressJS route

As a newcomer to NodeJS and Express, I am trying to create a simple '/' route that points to Angular's default index.html file located at client/src/index.html. This file contains the app-root tag. While the '/' route successfully ...

Showing nested arrays in API data using Angular

I would like to display the data from this API { "results": [ { "name": "Luke Skywalker", "height": "172", "mass": "77", & ...

Enhancing Twilio LocalVideoTrack with custom start and stop event handling

Is it possible to customize the events triggered when a video starts or stops playing? I attempted the code below, but unfortunately, it did not yield any results: this.videoTrack = screenTrack as LocalVideoTrack; this.videoTrack.stopped = function (eve ...

What is the process to convert it into an Array of Objects within Angular 2?

I have been working tirelessly for the past few days to create an Array of Objects that I can store in Local Storage. The main challenge I am facing is retrieving the existing value from Local Storage. After retrieving the existing array, I need to add th ...

Having trouble importing the UpgradeModule from @angularupgradestatic in Angular version 2.2.1

I am in the process of updating my AngularJS (ng1) application to Angular 2 (ng2). My Angular version is 2.2.1. Upon importing UpgradeModule from @angular\upgrade\static, I encountered the following exceptions: Uncaught SyntaxError: Unexpected ...

What steps are required to transform a TypeScript class with decorators into a proper Vue component?

When I inquire about the inner workings of vue-class-component, it seems that my question is often deemed too broad. Despite examining the source code, I still struggle to grasp its functionality and feel the need to simplify my understanding. Consider th ...

Guide to accessing Angular app on a mobile device within the same network

I'm facing an issue with my Angular App when trying to access it on mobile within the same network. I've attempted running ng serve --host <my IP> or ng serve --host 0.0.0.0 and it works well. However, the problem arises because the applica ...

Tips for creating a mapped type in TypeScript that is based on an array

Is there a way to create a function with dynamic properties? function magic(...propertyNames:string[]): { ????? : any } { .... } Could the returned type have properties listed in propertyName? For instance: type ResultType = {alpha:any, bravo:any}; le ...

Transforming a JSON file that has been previously converted to an Observable into a TypeScript map within an Angular application

There is a json data file named dummy, with the following structure: [ {"key":"KEY1", "value":["alpha","beta","gamma"]}, {"key":"KEY2", "value":["A","B","C"]}, {"key":"KEY3", "value":["One","Foo","Bar"]} ] The goal is to convert this json f ...

Tips on preventing Realtime database onWrite trigger function callback from iterating through data that has been altered

I am currently developing a 1 vs 1 game matching system using a real-time database. The system works by creating a record in the users table when a user signs in. Once there are two players with a status of placeholder, a cloud function generates a gameInf ...

Sequelize.js: Using the Model.build method will create a new empty object

I am currently working with Sequelize.js (version 4.38.0) in conjunction with Typescript (version 3.0.3). Additionally, I have installed the package @types/sequelize at version 4.27.25. The issue I am facing involves the inability to transpile the followi ...

Ecommerce Template for Next.js

I am new to the world of web development and I have a project involving customizing a Next.js ecommerce template. Since I'm still learning programming, I would appreciate a simple summary of the steps I need to take in order to achieve this. The speci ...

Using Typescript to override an abstract method that has a void return type

abstract class Base{ abstract sayHello(): void; } class Child extends Base{ sayHello() { return 123; } } The Abstract method in this code snippet has a return type of void, but the implementation in the Child class returns a number. S ...

Tips for automatically setting a default radio button selection in Angular 8

I am a beginner in Angular 8 and I am struggling with setting one of the radio buttons to be checked by default. I have attempted adding attributes like [checked]="true", checked but the issue persists. HTML <div class="form-check"> <mat-ra ...

Implementing conditional asynchronous function call with identical arguments in a Typescript React project

Is there a way in React to make multiple asynchronous calls with the same parameters based on different conditions? Here's an example of what I'm trying to do: const getNewContent = (payload: any) => { (currentOption === myMediaEnum.T ...