当mat-datepicker模型值小于最小日期时,Angular Material-Form变得无效



我在表单上使用mat日期选择器。我正在插入一些记录。这与表单验证配合良好。但是,当我试图更新同一记录时,我的表格显示为无效。这是由于日期无效。

表单显示无效时的情况-最小日期大于模型值时

为什么会发生这种情况?这是默认行为吗?如何使其发挥作用?

component.html

<form class="form-container" #pointAllocationForm="ngForm" (ngSubmit)="onSubmit()">
<mat-form-field class="example-full-width">
<div class="start-date">
<label class="required"><strong>Start Date : </strong></label>
<mat-form-field>
<input matInput [matDatepicker]="startDatepicker" [min]="minDate" placeholder="Choose a date" name="StartDate"
[(ngModel)]="myDate" #StartDate="ngModel" (ngModelChange)="setEndDate($event)" required>
<mat-datepicker-toggle matSuffix [for]="startDatepicker"></mat-datepicker-toggle>
<mat-datepicker #startDatepicker></mat-datepicker>
<mat-error *ngIf="StartDate.invalid && (StartDate.dirty || StartDate.touched)">Please enter a valid date.</mat-error>
</mat-form-field>
</div>
</mat-form-field>
<button class="btn btn-success" type="submit" [disabled]="pointAllocationForm.invalid">
Update Points </button>
</form>

组件.ts

import {Component} from '@angular/core';

@Component({
selector: 'datepicker-min-max-example',
templateUrl: 'datepicker-min-max-example.html',
styleUrls: ['datepicker-min-max-example.css'],
})
export class DatepickerMinMaxExample {
minDate = new Date();
myDate = new Date(2018, 9, 10);
}

我想我找到了一个适用于我的案例的解决方案:

template: [min]="formGroup.get('date').value ? formGroup.get('date').value : todayDate"
in code: todayDate = new Date();

意味着,我将来自后端的日期设置为min,否则为今天。当一个日期被选定时,它永远不会比最初给定的日期少。但这当然要求给定的日期是有效的。

可能为时已晚,但如果在填充formControl后从FormComponent调用setErrors(null(函数,它将变为有效的

最新更新