首页 > 解决方案 > 在 html datepicker 上动态设置 minDate/maxDate

问题描述

我需要限制我的日期选择器,以便 16 岁以下的人在 16 岁之前无法在日历上选择他们的生日。

我正在使用Angular datepicker,并且在我的打字稿文件中使用此代码没有问题:

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 };

这是我的 HTML:

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

我遇到的问题是默认的 html datepicker,我需要使用这个 datepicker 而不是 ngb-datepicker。我找到的所有解决方案都使用 jQuery,但我不能将它与 Angular 6 一起使用。

希望我说清楚了,希望你能帮我解决这个问题!

谢谢你。

预计到达时间:

这是我的问题的解决方案: 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">

标签: angulartypescriptdatepicker

解决方案


在这里使用时刻来形成日期

演示

参考----> 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">

推荐阅读