html date控件max值为今天,在HTML日期选择器上动态设置minDate / maxDate

本文介绍了如何在Angular应用中限制HTML date输入控件,使其只能选择16岁以上的日期,用于设置生日。作者使用当前日期动态计算最小和最大日期,但在尝试使用Angular 6时遇到了问题,因为找到的解决方案依赖于jQuery。最终,通过引入moment.js库并格式化日期,作者解决了问题,使得max和min属性能够正确设置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我需要限制日期选择器,以使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:

type="date" maxDate="maxDate" minDate="minDate"

jhiTranslate="form.birthdate.placeholder"

ngModel name="birthdate" #birthdate="ngModel">

我遇到的问题是默认的html datepicker,我需要使用此datepicker而不是ngb-datepicker。我找到的所有解决方案都使用jQuery,但无法在Angular 6中使用。

希望我能说清楚,您可以帮我解决这个问题!

谢谢。

ETA:

这是我的问题的解决方案:

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:

type="date" [max]="maxDate" [min]="minDate"

jhiTranslate="form.birthdate.placeholder"

ngModel name="birthdate" #birthdate="ngModel">

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值