[Fixed] set datepicker value automatically based on previous datepicker in angular(setvalue)

Issue

I have two datepickers picker1 and picker2. What I am trying to to is that when I select a date in picker1 the picker2 should automatically get selected and the date in the picker2 should be 60 days from date in picker1

For example if its march 1 2021 in picker1 It should be april 29 2021 in picker2

I have searched for various solutions in stackoverflow but couldn’t get the exact solution.
Pleease help if u guys know

Datepicker1:

                       <td>
                          <mat-form-field >
                            <input matInput readonly [matDatepicker]="picker1" formControlName="startdate" 
                            (dateChange)="setDate($event.value)"placeholder="Start Date">
                            <mat-datepicker-toggle matSuffix [for]="picker1"></mat-datepicker-toggle>
                            <mat-datepicker #picker1></mat-datepicker>
                        </mat-form-field>
                    </td>

Datepicker2

                    <td>
                        <mat-form-field>
                            <input matInput readonly [matDatepicker]="picker2" formControlName="enddate" 
                              placeholder="End Date">
                            <mat-datepicker-toggle matSuffix [for]="picker2"></mat-datepicker-toggle>
                            <mat-datepicker #picker2></mat-datepicker>
                        </mat-form-field>
                    </td>

My ts

    setDate(a) {
            this.datecheck = this.eventaddform.value.startdate+60
this.eventaddform.patchValue({
          expirydate: this.datecheck
    
    
        })
       }
  

I have created a sample stackblitz justincase if u guys need something to work with

Stackblitz: https://stackblitz.com/edit/angular-date-picker-sample-fr-h19bes?file=app%2Fapp.component.html

Solution

Use dateChange event from picker1 to set picker2 by binding value

I’ve created a basic stackblitz example removing Forms

DEMO

PS: adding 60 to March 01 2021 gave me April 30 2021. So you can try adding 59

Leave a Reply

(*) Required, Your email will not be published