@@ -135,6 +135,13 @@ export class MatAutocompleteTrigger implements ControlValueAccessor, OnDestroy {
135
135
/** Subscription to viewport size changes. */
136
136
private _viewportSubscription = Subscription . EMPTY ;
137
137
138
+ /**
139
+ * Whether the autocomplete can open the next time it is focused. Used to prevent a focused,
140
+ * closed autocomplete from being reopened if the user switches to another tab and then
141
+ * comes back.
142
+ */
143
+ private _canOpenOnNextFocus = true ;
144
+
138
145
/** Stream of keyboard events that can close the panel. */
139
146
private readonly _closeKeyEventStream = new Subject < void > ( ) ;
140
147
@@ -178,9 +185,20 @@ export class MatAutocompleteTrigger implements ControlValueAccessor, OnDestroy {
178
185
@Optional ( ) @Host ( ) private _formField : MatFormField ,
179
186
@Optional ( ) @Inject ( DOCUMENT ) private _document : any ,
180
187
// @deletion -target 7.0.0 Make `_viewportRuler` required.
181
- private _viewportRuler ?: ViewportRuler ) { }
188
+ private _viewportRuler ?: ViewportRuler ) {
189
+
190
+ if ( typeof window !== 'undefined' ) {
191
+ _zone . runOutsideAngular ( ( ) => {
192
+ window . addEventListener ( 'blur' , this . _windowBlurHandler ) ;
193
+ } ) ;
194
+ }
195
+ }
182
196
183
197
ngOnDestroy ( ) {
198
+ if ( typeof window !== 'undefined' ) {
199
+ window . removeEventListener ( 'blur' , this . _windowBlurHandler ) ;
200
+ }
201
+
184
202
this . _viewportSubscription . unsubscribe ( ) ;
185
203
this . _componentDestroyed = true ;
186
204
this . _destroyPanel ( ) ;
@@ -375,7 +393,9 @@ export class MatAutocompleteTrigger implements ControlValueAccessor, OnDestroy {
375
393
}
376
394
377
395
_handleFocus ( ) : void {
378
- if ( this . _canOpen ( ) ) {
396
+ if ( ! this . _canOpenOnNextFocus ) {
397
+ this . _canOpenOnNextFocus = true ;
398
+ } else if ( this . _canOpen ( ) ) {
379
399
this . _previousValue = this . _element . nativeElement . value ;
380
400
this . _attachOverlay ( ) ;
381
401
this . _floatLabel ( true ) ;
@@ -613,4 +633,12 @@ export class MatAutocompleteTrigger implements ControlValueAccessor, OnDestroy {
613
633
return ! element . readOnly && ! element . disabled && ! this . _autocompleteDisabled ;
614
634
}
615
635
636
+ /**
637
+ * Event handler for when the window is blurred. Needs to be an
638
+ * arrow function in order to preserve the context.
639
+ */
640
+ private _windowBlurHandler = ( ) => {
641
+ this . _canOpenOnNextFocus =
642
+ document . activeElement !== this . _element . nativeElement || this . panelOpen ;
643
+ }
616
644
}
0 commit comments