Chris
Chris

Reputation: 2015

Angular datepicker not updating after changing min or max date

I have a datepicker inside a mat-card like this:

<mat-card class="datepickerContainer">
    <mat-form-field appearance="fill">
        <mat-label>Month and Year</mat-label>
        <input matInput [min]="minDate" [max]="maxDate" [matDatepicker]="datePicker" [formControl]="date">
        <mat-datepicker-toggle matSuffix [for]="datePicker"></mat-datepicker-toggle>
        <mat-datepicker #datePicker
                        startView="multi-year"
                        (yearSelected)="yearSelectedHandler($event)"
                        (monthSelected)="monthSelectedHandler($event, datePicker)"
                        panelClass="example-month-picker">
        </mat-datepicker>
    </mat-form-field>
</mat-card>

Inside ngAfterViewInit(), the min selectable year is set like this based on the year specified in a configuration object:

  ngAfterViewInit(): void {
    this.configService.getConfiguration().subscribe((configs) => {
      this.minDate.setFullYear(configs.startYear);
    });
  }

I already debugged this and this.minDate.setFullYear() is being called with the correct year as parameter. However, when I now open the date picker in the frontend, it seems to be completely disabled:

datepicker disabled

I can click on the selected year (2022) but then I cannot select a month:

select month disabled

I do not disable the date picker anywhere, so why is it disabled and why is the min year not set to 2021? I also noticed that when I initially set the min date to something else (like 2021) already, it is working fine, so the problem must be related to Angular not knowing that I changed the min date in ngAfterViewInit().

Upvotes: 1

Views: 2704

Answers (1)

JMS
JMS

Reputation: 61

You have to call

ChangeDetectorRef.markForCheck()

after

this.minDate.setFullYear(configs.startYear);

Or else Angular will not know anything changed, since Angular detects changes if the reference of an @Input changes and not if the bound object is mutated.

Upvotes: 1

Related Questions