2

Currently, I am working on angular project where i have two angular date picker and i need to update second date picker value by adding 7 days from the first date picker value

template file
    <form [formGroup]="form">
           
            <input
              matInput
              [matDatepicker]="picker2"
              formControlName="dateOne"
            />
            <mat-datepicker-toggle matSuffix [for]="picker2"></mat-datepicker-toggle>
            <mat-datepicker #picker2></mat-datepicker>

            <input
              matInput
              [matDatepicker]="picker3"
              formControlName="dateTwo"
              class="mainfield"
            />
            <mat-datepicker-toggle matSuffix [for]="picker3"></mat-datepicker-toggle>
</form>
ts file
  form = this.fb.group(
    {
    
     dateOne: ["", [Validators.required]],
     dateTwo: ["", [Validators.required]],
}
)
0

2 Answers 2

2

As you are using Angular Reactive forms, you can listen for changes in the dateOne form control value through the valueChanges observable and set the dateTwo form control value.

    this.form.get('dateOne')?.valueChanges.subscribe(date => {
      const dateTwo = new Date(new Date(date).setDate(date.getDate() + 7));
      this.form.get('dateTwo')?.setValue(dateTwo);
    });

PS: In question the form control names differ in ts and html file. The above code snippet assumes the control names are dateOne and dateTwo respectively.

Sign up to request clarification or add additional context in comments.

Comments

0

As you are using Angular Reactive forms, you can listen for changes in the dateOne form control value through the valueChanges observable and set the dateTwo form control value.

this.form.get('dateOne')?.valueChanges.subscribe(date => {
  const dateTwo = formatDate(new Date()+ 7, 'MM/dd/yyyy', 'en');
  this.form.get('dateTwo')?.setValue(dateTwo);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.