Angular 8:如何使用[分钟]日期验证将表单控件值修补到mat-datepicker,并且表单控件日期值小于[分钟



如何使用 [min] 日期验证将表单控件值修补到 mat-datepicker 并且表单控件日期小于 [min] 日期?

这是html.

<label class="label input-form-label">Date:</label>
<span class="input-group-addon" (click)="picker.open();">
<input [matDatepicker]="picker" [min]="today" type="text" class="input-form" formControlName="date">
<div class="datepicker-icon-div" style="right: 30px;">
<i class="fa fa-calendar"></i>
</div>
</span>
<span>
<mat-datepicker #picker></mat-datepicker>
</span>

这是reactive form.

today = new Date(); // suppose todays date is 27-05-2020 
pastDate = new Date(2020, 05, 24);
this.form = this.fb.group({
date: [this.today, Validators.required]
})
patchFormValue(){
this.form.patchValue({
date: this.pastDate
})
}

我想从matdatepicker中禁用过去的日期,所以我在其中添加了 [min] 验证。但我也想修补过去的日期。 还有其他方法可以禁用日期或修补过去的日期吗?

我不确定您是否仍然需要这个,但我今天遇到了类似的事情,我们的值来自比今天的日期早的数据库,但我们不允许他们从选择器中选择较早的日期。

我最终做了一些对我有用的事情,尽管它并不漂亮。

首先,我在日期选择器中添加了一个 [dateClass]="dateClass((" 和 [startAt]="today",并摆脱了 [min] 验证。

<label class="label input-form-label">Date:</label>
<span class="input-group-addon" (click)="picker.open();">
<input [matDatepicker]="picker" type="text" class="input-form" formControlName="date">
<div class="datepicker-icon-div" style="right: 30px;">
<i class="fa fa-calendar"></i>
</div>
</span>
<span>
<mat-datepicker [startAt]="today" [dateClass]="dateClass()" #picker></mat-datepicker>
</span>

然后,我将该方法添加到 component.ts 中,以便它将为今天日期之前的所有值添加新的 css 样式。

dateClass() {
return (date: Date): MatCalendarCellCssClasses => {
return  date.setHours(0, 0, 0, 0) < this.today.setHours(0, 0, 0, 0) ? 'disable-dates' : undefined;
}
}

然后我将那个 css 类添加到我的组件中,这样它就可以从日期选择器中模拟垫子禁用日期的样式

::ng-deep.disable-dates {
pointer-events: none;
}
::ng-deep.disable-dates > .mat-calendar-body-cell-content {
color: rgba(0, 0, 0, 0.38);
}

这样,它将禁用日期选取器中的日期,但不会导致在选取器附加到的输入字段上进行验证。

https://stackblitz.com/edit/angular-ivy-atw9cz

In Js Month 索引为零,所以 May == 4

https://stackblitz.com/edit/angular-ivy-aeasyj

最新更新