angular - 在 html datepicker 上动态设置 minDate/maxDate

标签 angular typescript datepicker

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

我使用的是 Angular datepicker,在我的 typescript 文件中使用这段代码没有问题:

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 日期选择器,我需要使用这个日期选择器而不是 ngb-datepicker。我找到的所有解决方案都使用 jQuery,但我不能将它与 Angular 6 一起使用。

希望我说清楚了,希望你能帮助我!

谢谢。

预计到达时间:

这是我的问题的解决方案: 应用程序组件.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">

最佳答案

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

DEMO

引用----> 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">

关于angular - 在 html datepicker 上动态设置 minDate/maxDate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52035029/

相关文章:

javascript - 如果我通过 HTML 中的插值添加正则表达式,为什么会更改它?

angular - 在 Angular 2 中更改 ViewChild 上的元素类

angular - 在 Angular 7 中实现 bcrypt

javascript - 将 AxiosPromise 更改为常规 Promise 的正确方法,同时避免 Promise 构造函数反模式

javascript - 如何忽略 typescript 中的 "Cannot find name ' M'“错误?

ruby-on-rails - Rails 4 - 将日期时间转换为单独的日期和时间字段

加载图像时 Angular 4 空调用

angular - 为什么在 typescript 的 const 中使用带有 ${ 的反勾

javascript - 如何在 ng-include Angular JS 中使用 Foundation CSS Calendar

Python Selenium + Datepicker 问题