@@ -135,6 +135,13 @@ export class MatAutocompleteTrigger implements ControlValueAccessor, OnDestroy {
135135 /** Subscription to viewport size changes. */
136136 private _viewportSubscription = Subscription . EMPTY ;
137137
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+
138145 /** Stream of keyboard events that can close the panel. */
139146 private readonly _closeKeyEventStream = new Subject < void > ( ) ;
140147
@@ -178,9 +185,20 @@ export class MatAutocompleteTrigger implements ControlValueAccessor, OnDestroy {
178185 @Optional ( ) @Host ( ) private _formField : MatFormField ,
179186 @Optional ( ) @Inject ( DOCUMENT ) private _document : any ,
180187 // @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+ }
182196
183197 ngOnDestroy ( ) {
198+ if ( typeof window !== 'undefined' ) {
199+ window . removeEventListener ( 'blur' , this . _windowBlurHandler ) ;
200+ }
201+
184202 this . _viewportSubscription . unsubscribe ( ) ;
185203 this . _componentDestroyed = true ;
186204 this . _destroyPanel ( ) ;
@@ -375,7 +393,9 @@ export class MatAutocompleteTrigger implements ControlValueAccessor, OnDestroy {
375393 }
376394
377395 _handleFocus ( ) : void {
378- if ( this . _canOpen ( ) ) {
396+ if ( ! this . _canOpenOnNextFocus ) {
397+ this . _canOpenOnNextFocus = true ;
398+ } else if ( this . _canOpen ( ) ) {
379399 this . _previousValue = this . _element . nativeElement . value ;
380400 this . _attachOverlay ( ) ;
381401 this . _floatLabel ( true ) ;
@@ -613,4 +633,12 @@ export class MatAutocompleteTrigger implements ControlValueAccessor, OnDestroy {
613633 return ! element . readOnly && ! element . disabled && ! this . _autocompleteDisabled ;
614634 }
615635
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+ }
616644}
0 commit comments