Search code examples
angularautocompleteangular-materialangular-material2angular-material-7

Angular Material Autocomplete control once Opened is not getting closed for external actions like Page level scroll


As shown in the stackblitz, I'm facing an issue with Angular Material Autocomplete control in which the control stays opened on external events like Page Scroll as shown in the attached sample and the issues even occurs in the Angular Material demo site. Issue Screenshot

Steps to reproduce:

  1. Click on Autocomplete control and let it stay expanded.

  2. Try to do page level scroll to the bottom (https://v7.material.angular.io/components/autocomplete/examples), the Autocomplete control doesn't collapse/close.

  3. I've tried to place focusout event as in the example (https://stackblitz.com/edit/angular-jfuvpb?file=app%2Fautocomplete-overview-example.html), even though the Autocomplete control collapses on Page level scroll click (https://stackblitz.com/edit/angular-jfuvpb?file=app%2Fautocomplete-overview-example.ts) but on more issue came up like the selected option doesn't apply to Autocomplete control.

Expected Behavior: On any action outside of the Autocomplete control e.g., Page level scroll should close the Autocomplete control

Actual Behavior: The Autocomplete control stays expanded and is not user friendly behavior.


Solution

  • It's well-know issue in github

    The workaround for that is to put cdkScrollable on your wrapper that has scroll and override MAT_AUTOCOMPLETE_SCROLL_STRATEGY provider.

    html

    <div class="content-container" cdkScrollable>
    

    Make sure you imported import {ScrollingModule} from '@angular/cdk/scrolling';

    Note: you don't need to put cdkScrollable if it is a body scroll

    app.module.ts

    import { Overlay, CloseScrollStrategy } from '@angular/cdk/overlay';
    
    export function scrollFactory(overlay: Overlay): () => CloseScrollStrategy {
        return () => overlay.scrollStrategies.close();
    }
    
    @NgModule({
      ...
      providers: [
        { provide: MAT_AUTOCOMPLETE_SCROLL_STRATEGY, useFactory: scrollFactory, deps: [Overlay] }
      ]
    })
    export class AppModule {}
    

    Forked Stackblitz