I am building a component (html, css, spec.ts, ts) in angular in which I always want endDate > startDate. I have followed this link https://material.angular.io/components/datepicker/overview in order make multiple datepickers.
Below is my HTML for startDate
and endDate
:
startDate:
<div class="start-date" fxFlex="50%" fxFlexOrder="1">
<mat-form-field>
<input matInput [matDatepicker]="picker1" placeholder="{{'PORTAL.STARTDATE' | translate}}" type="text" formControlName="startDate" [(ngModel)]="unavailability.startDate" [readonly]="!componentPermission.writePermission">
<mat-datepicker-toggle matSuffix [for]="picker1"></mat-datepicker-toggle>
<mat-datepicker #picker1></mat-datepicker>
</mat-form-field>
</div>
endDate:
<div class="end-date" fxFlex="50%" fxFlexOrder="2">
<mat-form-field>
<input matInput [matDatepicker]="picker2" placeholder="{{'PORTAL.ENDDATE' | translate}}" type="text" formControlName="endDate" [(ngModel)]="unavailability.endDate" [readonly]="!componentPermission.writePermission">
<mat-datepicker-toggle matSuffix [for]="picker2"></mat-datepicker-toggle>
<mat-datepicker #picker2></mat-datepicker>
</mat-form-field>
</div>
Now below is my angular code (ts) where I am calling validateForm
method on the page load.
ngOnInit() {
....
this.validateForm();
}
validateForm() {
this.unavailabilityForm = this.formBuilder.group({
'startDate': ['', Validators.required],
'endDate': ['', Validators.required],
'unavailabilityReason': ['']
});
}
ProblemStatement:
Now what I need to do is - if I have selected any date in startDate
(for example 23rd Nov), then in the endDate
datepicker all the dates before and including 23rd Nov should be disabled so that I can only select dates after 23rd Nov only. Is this possible to do in Angular?
Can we achieve that by placing minDate
and maxDate
somewhere in HTML or TS ?
Since you are using a reactive form, utilize the form controls. It's not recommended to have two bindings (
ngModel
andformControl
). So drop thengModel
like I suggested in a previous question of yours: https://stackoverflow.com/a/47426879/6294072So populate your form controls with the values of from your object
unavailability
.if you are receiving the values at a later point you can use
patchValues
:else you can set the values when you build the form.
Then the only thing you need to add to your second datepicker is
[min]
like the other answer mentioned. There utilize the form control value:DEMO
I used
and worked like expected (disabled endDate calendar previous dates from selected date in startDate Calendar)Binding with [min] works perfect for any date
.ts file
.html file
Unless I'm missing something, you can use the
[min]=""
date property:Whatever
startDate
is will limit the Calendar dates available forendDate
. If you need it set beforestartDate
is chosen, use another variable and set it inconsturctor()
orngOnInit()
of your component.See: https://material.angular.io/components/datepicker/overview#date-validation