Angular Material数据选择器具有自定义格式并过滤可用日期

时间:2019-05-06 12:28:33

标签: javascript angular typescript date angular-material

我想获得类似于https://material.angular.io/components/datepicker/examples的效果,其中日期的格式类似于上一个示例“具有自定义格式的日期选择器”。但是我已经在使用“带有过滤器验证的Datepicker”以及“带有最小和最大验证的Datepicker”。这两个使用JavaScript的Date()创建日期,并且工作正常。但是将所有这些结合在一起使我很费劲,因为显示的格式是即时的,而max / min / filter验证使用的是JS的新Date()。保留它可能很好,并且在此之上仅显示过滤后的日期,但以诸如“具有自定义格式的日期选取器”中的时刻格式显示。

编辑:添加了源代码

contact.component.html

<mat-form-field>
  <input
    matInput
    [matDatepicker]="deadlineDatepicker"
    [matDatepickerFilter]="filterAvailableDays"
    [max]="maxDate"
    [min]="currentDate"
    formControlName="formControlDeadline"
    aria-label="Click here to choose a deadline for your project."
    placeholder="Project deadline"
    title="Project deadline"
  />
  <mat-hint
    >Specify when at latest you would like to have the project
    done.</mat-hint
  >
  <mat-error *ngIf="!contactForm.get('formControlDeadline')!.valid"
    >This date is <strong>out of our scope</strong>.
  </mat-error>
  <mat-datepicker-toggle
    matSuffix
    [for]="deadlineDatepicker"
  ></mat-datepicker-toggle>
  <mat-datepicker touchUi="true" #deadlineDatepicker></mat-datepicker>
</mat-form-field>

contact.component.ts

export class ContactComponent {
  public currentDate: Date = new Date();

  // Create max deadline dynamically 5 years from now.
  public day: number = this.currentDate.getDate();
  public month: number = this.currentDate.getMonth();
  public year: number = this.currentDate.getFullYear();
  public maxDate: Date = new Date(this.year + 5, this.month, this.day);

  constructor(private formBuilder: FormBuilder) {
    this.contactForm = this.formBuilder.group({
      formControlDeadline: ''
    });
  }

  /**
   * @description Filter available days in the datepicker to choose.
   * @param {d} - instance of date.
   * @returns {boolean}
   */
  public filterAvailableDays = (d: Date): boolean => {
    const day = d.getDay();
    return day !== 0 && day !== 6; // Prevent Saturday and Sunday from being selected.
  };
}

0 个答案:

没有答案