Home > Enterprise >  Angular material date picker add dates automatically
Angular material date picker add dates automatically

Time:01-09

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"
              
            />
            <mat-datepicker-toggle matSuffix [for]="picker3"></mat-datepicker-toggle>
</form>
ts file
  form = this.fb.group(
    {
    
     dateOne: ["", [Validators.required]],
     dateTwo: ["", [Validators.required]],
}
)

CodePudding user response:

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.

  •  Tags:  
  • Related