I am working with a Mat date range picker where the start date and end date are form controls in the ts code for the component.
To retrieve the values of the date picker, I am using the combineLatest method on the start and end date.
The issue I am facing is that when I initially select a start date/end date, the code executes correctly. However, if I go back and modify either date, the combineLatest function is triggered immediately when I click on a start date because the end date already has a value.
How can I make the code wait for both the start date and end date to change before executing?
Parent ts code -
dateRangeStart: FormControl = new FormControl();
dateRangeEnd: FormControl = new FormControl();
...
...
...
combineLatest([
this.dateRangeStart.valueChanges,
this.dateRangeEnd.valueChanges
]).subscribe((dates) => {
//logic
}
})
Parent HTML
<app-date-picker
[dateRangeStart]="dateRangeStart"
[dateRangeEnd]="dateRangeEnd">
</app-date-picker>
DatePicker TS
@Input() dateRangeStart!: FormControl;
@Input() dateRangeEnd!: FormControl;
maxDate: Date | undefined = undefined;
constructor() { }
ngOnInit(): void {
this.dateRangeStart.valueChanges.subscribe(dateRangeStart => {
if (!!dateRangeStart) {
const maxDate = new Date(dateRangeStart);
maxDate.setDate(maxDate.getDate() + 7);
this.maxDate = maxDate;
} else {
this.maxDate = undefined;
}
})
}
DatePicker HTML
<div>
<mat-form-field appearance="fill">
<mat-label>Enter a date range</mat-label>
<mat-date-range-input
[rangePicker]="picker"
[max]="maxDate">
<input
matStartDate
[formControl]="dateRangeStart"
placeholder="Start date">
<input
matEndDate
[formControl]="dateRangeEnd"
placeholder="End date">
</mat-date-range-input>
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-date-range-picker #picker></mat-date-range-picker>
</mat-form-field>
</div>