角材料-垫日期选择器模型值小于最小日期时,表单变得无效

时间:2018-10-30 06:36:34

标签: angular angular-material angular-material2

我在表格上使用了日期选择器。我正在插入一些记录。表单验证可以很好地工作。但是,当我尝试更新同一记录时,则我的表单显示无效。这是由于日期无效。

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

为什么会这样?这是默认行为吗?如何运作?

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>

component.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);
}

1 个答案:

答案 0 :(得分:0)

我想我找到了一种适用于我的情况的解决方案:

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

意味着,我将后端的日期设置为分钟,否则设置为今天。选择日期后,日期将永远不会少于原始日期。但这当然要求给定日期是有效的。