Angular Material-Datepicker使所选值一个月达到最大值

时间:2018-08-28 15:29:25

标签: angular datepicker angular-material

我有两个日期选择器。一个选择“ fromDate”,另一个选择 “至今”。除了用户首先要选择fromDate之外,toDate的最大值应为fromDate一个月。

最大值将禁止用户选择从startDate / fromDate开始超过30天的日期。

角度材料doc #datevalidation https://material.angular.io/components/datepicker/overview#choosing-a-date-implementation-and-date-format-settings

HTML:

<mat-form-field class="datepicker">
        <input matInput [matDatepicker]="frompicker" placeholder="from" [formControl]="fromDate">
        <mat-datepicker-toggle matSuffix [for]="frompicker"></mat-datepicker-toggle>
        <mat-datepicker #frompicker></mat-datepicker>
      </mat-form-field>

      <mat-form-field class="datepicker">
        <input matInput [max]="maxDate" [matDatepicker]="topicker"  placeholder="to" [formControl]="toDate">
        <mat-datepicker-toggle matSuffix [for]="topicker"></mat-datepicker-toggle>
        <mat-datepicker #topicker></mat-datepicker>
      </mat-form-field>

Ts文件:

  setMaxDateForCalender(){

    let fullyear = this.datePipe.transform(this.fromDate.value, "yyyy");

    this.maxDate = new Date();
    this.maxDate.setDate(this.fromDate.value.getDate());
    this.maxDate.setMonth(this.fromDate.value.getMonth() + 1);
    this.maxDate.setFullYear(Number(fullyear));

    console.log("Max Date After: " + this.datePipe.transform(this.maxDate, this.dateFormat));
  }

我尝试了不同的方法来执行此操作,但是在选择fromDate之后似乎没有触发最大值。

1 个答案:

答案 0 :(得分:1)

您使用的是Reactive表单,formControl还是ngModel?在哪里调用函数setMaxDateForCalendar()?

//if you're using ReactiveForm
..AFTER you create the form...
this.myForm.get('fromDate').valueChanges
        .subscribe((date:any) => {
            ..use "date", NOT this.myForm.value.fromDate
        })

//If this.fromDate is a FormControl use
this.fromDate.valueChanges
        .subscribe((date:any) => {
            ..use "date", NOT this.fromDate.value
        })