diff --git a/src/lib/datepicker/datepicker.spec.ts b/src/lib/datepicker/datepicker.spec.ts index 81576b717270..32330bbaf579 100644 --- a/src/lib/datepicker/datepicker.spec.ts +++ b/src/lib/datepicker/datepicker.spec.ts @@ -113,6 +113,20 @@ describe('MatDatepicker', () => { .not.toBeNull(); }); + it('should open datepicker if opened input is set to true', async(() => { + testComponent.opened = true; + fixture.detectChanges(); + + expect(document.querySelector('.mat-datepicker-content')).not.toBeNull(); + + testComponent.opened = false; + fixture.detectChanges(); + + fixture.whenStable().then(() => { + expect(document.querySelector('.mat-datepicker-content')).toBeNull(); + }); + })); + it('open in disabled mode should not open the calendar', () => { testComponent.disabled = true; fixture.detectChanges(); @@ -1096,10 +1110,11 @@ describe('MatDatepicker', () => { @Component({ template: ` - + `, }) class StandardDatepicker { + opened = false; touch = false; disabled = false; date: Date | null = new Date(2020, JAN, 1); diff --git a/src/lib/datepicker/datepicker.ts b/src/lib/datepicker/datepicker.ts index ae0bd02aab63..7d94f8f27fab 100644 --- a/src/lib/datepicker/datepicker.ts +++ b/src/lib/datepicker/datepicker.ts @@ -186,7 +186,18 @@ export class MatDatepicker implements OnDestroy { @Output('closed') closedStream: EventEmitter = new EventEmitter(); /** Whether the calendar is open. */ - opened = false; + @Input() + get opened(): boolean { return this._opened; } + set opened(value: boolean) { + const shouldOpen = coerceBooleanProperty(value); + + if (shouldOpen) { + this.open(); + } else { + this.close(); + } + } + private _opened = false; /** The id for the datepicker calendar. */ id = `mat-datepicker-${datepickerUid++}`; @@ -277,7 +288,7 @@ export class MatDatepicker implements OnDestroy { /** Open the calendar. */ open(): void { - if (this.opened || this.disabled) { + if (this._opened || this.disabled) { return; } if (!this._datepickerInput) { @@ -288,13 +299,13 @@ export class MatDatepicker implements OnDestroy { } this.touchUi ? this._openAsDialog() : this._openAsPopup(); - this.opened = true; + this._opened = true; this.openedStream.emit(); } /** Close the calendar. */ close(): void { - if (!this.opened) { + if (!this._opened) { return; } if (this._popupRef && this._popupRef.hasAttached()) { @@ -314,7 +325,7 @@ export class MatDatepicker implements OnDestroy { this._focusedElementBeforeOpen = null; } - this.opened = false; + this._opened = false; this.closedStream.emit(); }