我的物料日期选择器控件(
dob
)定义如下。我遇到的问题是 [min]
和 [max]
(在 HTML 中设置)值不起作用 - dob
控件在输入日期的第一位数字后才有效。知道为什么吗?
HTNL:
<mat-form-field appearance="outline">
<mat-label>DOB</mat-label>
<input formControlName="dob" #ref matInput [min]="10" [max]="10" [matDatepicker]="picker" placeholder="Choose a date" required>
<mat-hint>{{DATE_FORMAT}}</mat-hint>
<mat-datepicker-toggle matIconSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
<mat-error *ngIf="f['dob'].errors">Invalid DOB</mat-error>
</mat-form-field>
模块:
const CUSTOM_MOMENT_FORMATS = {
parse: {
dateInput: 'yyyy-MM-DD',
},
display: {
dateInput: 'yyyy-MM-DD',
monthYearLabel: 'MMM YYYY',
dateA11yLabel: 'LL',
monthYearA11yLabel: 'MMMM YYYY',
},
};
...
providers: [
{provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE]},
{provide: MAT_DATE_FORMATS, useValue: CUSTOM_MOMENT_FORMATS},
],
最后在组件中:
ngOnInit() {
this.account.dob = moment(this.account.dob).format(Constants.dateFormat);
var test = moment(this.account.dob, Constants.dateFormat).toDate();
this.form = this.formBuilder.group({
title: [this.account.title, Validators.required],
firstName: [this.account.firstName, Validators.required],
lastName: [this.account.lastName, Validators.required],
email: [this.account.email, [Validators.required, Validators.email]],
dob: [moment(this.account.dob, Constants.dateFormat).toDate(), [Validators.required]],
password: ['', [Validators.minLength(6)]],
confirmPassword: ['', [Validators.minLength(6)]],
phoneNumber: [this.account.phoneNumber ], // Phone number is optional
}, {
validator: [MustMatch('password', 'confirmPassword')]
});
}
[min]
和 [max]
应该是实际日期。
如果[min]
是从现在起10天前,而[max]
是从现在起10天后,你可以这样做。
ts
minDate = new Date(new Date().getTime() - 10*86400);
maxDate = new Date(new Date().getTime() + 10*86400);
ngOnInit() {
// your code
}
html
<input formControlName="dob" #ref matInput [min]="minDate" [max]="maxDate" [matDatepicker]="picker" placeholder="Choose a date" required>