简体   繁体   中英

Material calendar how to select max and min date?

I am using material calendar and i want user to select one month date only. I use minData and maxDate field. minDate is working but maxDate not working.

exmple.component.html

<mat-calendar [selected]="selectedDate" (selectedChange)="onCalendarSelectedChange($event)" [minDate]="today" [maxDate]="maxDate"></mat-calendar>

Here is the given link:

https://angular-pknsri.stackblitz.io

Please help me.

Actually you have change the stackblitz with anil's answer. So i am updating what could have possibly gone wrong. You should create two different date objects for min and max separately.

 var minCurrentDate = new Date();
    var maxNewDate = new Date();
    this.minDate = minCurrentDate;
    this.maxDate  = maxNewDate.setMonth(maxNewDate.getMonth()+1);

    // this.minDate = new Date(2000, 0, 1);
    // this.maxDate = new Date(2020, 0, 1);
    console.log(this.maxDate, minCurrentDate,maxNewDate, maxNewDate.getMonth());

When you did setMonth() on the current date you changed the reference for min date as well. Both your minDate and max date were pointing to the same thing. After all object was the same, only the references changed. So try creating two different objects and check.

PS: Farhat raced me :P. I didn't see it.

in html

<mat-form-field class="example-full-width">
  <input matInput [min]="minDate" [max]="maxDate" [matDatepicker]="picker" placeholder="Choose a date">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

in ts file

 minDate = new Date(2000, 0, 1);
  maxDate = new Date(2020, 0, 1);

Reference https://material.angular.io/components/datepicker/examples

这是一个可以帮助您的日期选择器的示例: StackBlitz HERE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM