如何在Datepicker中禁用过往日期及所有周六周日?
实现禁用过往日期及周末的Datepicker
你的现有代码已经通过min="{{ minimumDate }}"实现了禁用过往日期,这部分逻辑是正确的:
minimumDate = new Date().toISOString().split('T')[0];
原生<input type="date">会自动过滤早于min属性值的日期选项。
但原生日期输入框没有内置禁用周末的属性,需要结合Angular的表单验证或自定义指令来实现,以下是两种可行方案:
方案一:响应式表单验证(阻止非法提交并提示)
这种方案会在用户选择/输入周末日期时,标记表单为非法并显示提示,适合需要严格校验数据的场景:
- 编写自定义验证器函数
import { AbstractControl, ValidatorFn } from '@angular/forms'; // 验证日期是否为周六或周日 export function weekendValidator(): ValidatorFn { return (control: AbstractControl): { [key: string]: any } | null => { if (!control.value) return null; // 空值不触发验证 const targetDate = new Date(control.value); const dayOfWeek = targetDate.getDay(); // 0=周日,6=周六 return (dayOfWeek === 0 || dayOfWeek === 6) ? { isWeekend: true } : null; }; }
- 将验证器绑定到表单控件
import { FormBuilder, Validators } from '@angular/forms'; // 假设你的表单初始化逻辑如下 constructor(private fb: FormBuilder) { this.yourForm = this.fb.group({ date: ['', [Validators.required, weekendValidator()]] }); }
- 在模板中添加错误提示
<input class="col-lg-3 form-control form-control-lg" type="date" min="{{ minimumDate}}" id="form3Example1cg" placeholder="Date" formControlName="date" /> <!-- 周末选择错误提示 --> <div *ngIf="yourForm.get('date')?.hasError('isWeekend')" class="text-danger mt-1"> 请选择周一至周五的工作日 </div>
方案二:自定义指令(实时拦截周末选择)
如果希望用户无法选择周末(手动输入也会被重置),可以通过自定义指令实时拦截非法日期:
- 创建指令文件
prevent-weekend.directive.ts
import { Directive, HostListener } from '@angular/core'; import { NgControl } from '@angular/forms'; @Directive({ selector: '[appPreventWeekend]' }) export class PreventWeekendDirective { constructor(private ngControl: NgControl) {} @HostListener('change', ['$event']) onDateChange(event: Event): void { const inputEl = event.target as HTMLInputElement; const targetDate = new Date(inputEl.value); const dayOfWeek = targetDate.getDay(); if (dayOfWeek === 0 || dayOfWeek === 6) { inputEl.value = ''; this.ngControl.control?.setValue(''); alert('只能选择周一至周五的工作日'); } } }
- 在模块中声明并导出指令
import { PreventWeekendDirective } from './prevent-weekend.directive'; @NgModule({ declarations: [PreventWeekendDirective], exports: [PreventWeekendDirective] }) export class YourModule {}
- 在模板中启用指令
<input class="col-lg-3 form-control form-control-lg" type="date" min="{{ minimumDate}}" id="form3Example1cg" placeholder="Date" formControlName="date" appPreventWeekend />
推荐两种方案结合使用:用指令提升用户体验,用验证器确保提交数据的合法性。
内容的提问来源于stack exchange,提问作者rahim sayyad
相关产品推荐
相关产品推荐

