'Angular mat date range picker, wait for both start and end date to be selected with form control
I have a Mat date range picker defined. With the ts code for the component, the start date and end date are form controls.
For my to get the values of the date picker, I'm using the combineLatest on the start and end date.
My problem is that when I select the very initial starting date/ending date, it is executed as expected but when I go back and modify the starting date and ending date, the combineLatest is executed immediately when I click on a starting date because the ending date already has a value.
How do I wait for both the starting date and the ending date change before execution of code?
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>
Solution 1:[1]
Well I'm guessing when you "go back" you re-initialize datepicker ts component and combineLatest will take last valid values from the observables and execute immediately. Some solutions for you could be to:
- Flush
this.dateRangeStart.valueChanges, this.dateRangeEnd.valueChangesindatepicker tsusingngOnDestroylifecycle. - Move
combineLatestitself intodatepicker tsand have the parent subscribe to it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
