您需要在 HTML 中使用日期输入的 min 和 max 属性,否则,您只能使用响应式表单来验证日期值的存在,即 Validators.required。
导入FormsModule和ReactiveFormsModule并在app.module.ts中提供DatePipe
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@NgModule({
declarations: [],
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
],
providers: [
DatePipe,
],
bootstrap: [AppComponent],
})
export class AppModule {}
使用app.component(或您想要的组件)中的DatePipe 设置当前日期并格式化日期值。在ngOnInit 函数中设置默认日期值。使用表单作为输入的父元素(虽然不是必需的)。
app.component.ts
import { DatePipe } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
})
export class AppComponent implements OnInit {
form: FormGroup;
startDate: string;
endDate: string;
maxDate: string;
constructor(datePipe: DatePipe) {
const dateFormat = 'yyyy-MM-dd';
this.startDate = datePipe.transform(
new Date().setDate(new Date().getDate() - 1),
dateFormat
);
this.maxDate = this.endDate = datePipe.transform(new Date(), dateFormat);
}
ngOnInit(): void {
this.form = new FormGroup({
startDate: new FormControl(this.startDate, Validators.required),
endDate: new FormControl(this.endDate, Validators.required),
});
}
onDateChange(): void {
this.startDate = this.form.get('startDate').value;
this.endDate = this.form.get('endDate').value;
// some other important code here...
}
}
在HTML文件中,设置startDate日期输入的max属性不超过endDate日期输入值;反之亦然:将endDate 日期输入的min 属性设置为不超过startDate 日期输入值
app.component.html
<form [formGroup]="form">
<div>
<div>
<label for="start_date">Start date</label>
<input id="start_date" type="date" [max]="maxDate > endDate ? endDate : maxDate" (change)="onDateChange()" formControlName="startDate">
</div>
<div>
<label for="end_date">End date</label>
<input id="end_date" type="date" [min]="startDate" [max]="maxDate" (change)="onDateChange()" formControlName="endDate">
</div>
</div>
</form>