Search code examples
angulartypescriptdatepicker

Set minDate/maxDate dynamically on html datepicker


I need to restrict my datepicker so that people who are under 16 cannot select their birthdate on the calendar until the day they turn 16.

I was using Angular datepicker and had no problem to do it with this code in my typescript file:

now = new Date();
year = this.now.getFullYear();
month = this.now.getMonth();
day = this.now.getDay();
minDate = { year: this.year - 100, month: this.month, day: this.day };
maxDate = { year: this.year - 16, month: this.month + 1, day: this.day };

Here is my HTML:

<input class="form-control" [required]="mngVis.birthdate.isrequired" 
type="date" maxDate="maxDate" minDate="minDate" 
jhiTranslate="form.birthdate.placeholder"
ngModel name="birthdate" #birthdate="ngModel">

The issue I have is with the default html datepicker, and I need to use this datepicker and not ngb-datepicker. All the solution I find use jQuery but I cannot use it with Angular 6.

Hope I made myself clear and that you can help me with this !

Thank you.

ETA:

Here is the solution to my issue: app.component.ts :

import { Component } from '@angular/core';
import moment from 'moment'

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Angular';

  now = new Date();
  year = this.now.getFullYear();
  month = this.now.getMonth();
  day = this.now.getDay();
  minDate = moment({year: this.year - 100, month: this.month, day: this.day}).format('YYYY-MM-DD');

  maxDate = moment({year: this.year - 16, month: this.month, day: this.day}).format('YYYY-MM-DD');

  date(ev) {
    console.log(this.minDate)
    console.log(ev.target.value)
  }
}

HTML:

 <input class="form-control" [required]="mngVis.birthdate.isrequired" 
    type="date" [max]="maxDate" [min]="minDate" 
    jhiTranslate="form.birthdate.placeholder"
    ngModel name="birthdate" #birthdate="ngModel">

Solution

  • Using moment here for date formation

    DEMO

    Reference ----> https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date

    //Taken current date as min date. and random as max date. 
    // Default format of date is as "YYYY-MM-DD" so we need to convert using  moment  
    
    minDate = moment(new Date()).format('YYYY-MM-DD')
    maxDate ="2018-09-08"
    

    HTML:

    <input class="form-control" type="date" [min]="minDate" [max]="maxDate">