Skip to content

Commit 5db8dca

Browse files
authored
fix(material/datepicker): error if some methods are called too early. (#32630)
Fixes that the `focusActiveCell` and `updateTodaysDate` methods on `MatCalendar` were throwing an error if they're called too early. Fixes #32627.
1 parent efa0d4f commit 5db8dca

2 files changed

Lines changed: 29 additions & 3 deletions

File tree

src/material/datepicker/calendar.spec.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -639,6 +639,28 @@ describe('MatCalendar', () => {
639639
});
640640
});
641641
});
642+
643+
it("should not throw when updating today's date too early", () => {
644+
const fixture = TestBed.createComponent(StandardCalendar);
645+
const calendar = fixture.debugElement.query(By.directive(MatCalendar))
646+
.componentInstance as MatCalendar<Date>;
647+
648+
expect(() => {
649+
calendar.updateTodaysDate();
650+
fixture.detectChanges();
651+
}).not.toThrow();
652+
});
653+
654+
it('should not throw when focusing the active cell too early', () => {
655+
const fixture = TestBed.createComponent(StandardCalendar);
656+
const calendar = fixture.debugElement.query(By.directive(MatCalendar))
657+
.componentInstance as MatCalendar<Date>;
658+
659+
expect(() => {
660+
calendar.focusActiveCell();
661+
fixture.detectChanges();
662+
}).not.toThrow();
663+
});
642664
});
643665

644666
@Component({

src/material/datepicker/calendar.ts

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -499,12 +499,12 @@ export class MatCalendar<D> implements AfterContentInit, AfterViewChecked, OnDes
499499

500500
/** Focuses the active date. */
501501
focusActiveCell() {
502-
this._getCurrentViewComponent()._focusActiveCell(false);
502+
this._getCurrentViewComponent()?._focusActiveCell(false);
503503
}
504504

505505
/** Updates today's date after an update of the active date */
506506
updateTodaysDate() {
507-
this._getCurrentViewComponent()._init();
507+
this._getCurrentViewComponent()?._init();
508508
}
509509

510510
/** Handles date selection in the month view. */
@@ -557,7 +557,11 @@ export class MatCalendar<D> implements AfterContentInit, AfterViewChecked, OnDes
557557
}
558558

559559
/** Returns the component instance that corresponds to the current calendar view. */
560-
private _getCurrentViewComponent(): MatMonthView<D> | MatYearView<D> | MatMultiYearView<D> {
560+
private _getCurrentViewComponent():
561+
| MatMonthView<D>
562+
| MatYearView<D>
563+
| MatMultiYearView<D>
564+
| undefined {
561565
// The return type is explicitly written as a union to ensure that the Closure compiler does
562566
// not optimize calls to _init(). Without the explicit return type, TypeScript narrows it to
563567
// only the first component type. See https://github.com/angular/components/issues/22996.

0 commit comments

Comments
 (0)