Following solution works for me. Hope this will be a help to someone.
I added AutocompletePositionModule module.
Then added directive and used in many places in my project.
Module file
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { AutocompletePositionDirective } from './autocomplete-position.directive';
import { MatAutocompleteModule } from '@angular/material/autocomplete';
@NgModule({
declarations: [
AutocompletePositionDirective
],
exports: [
AutocompletePositionDirective
],
imports: [
CommonModule,
MatAutocompleteModule,
]
})
export class AutocompletePositionModule { }
Directive file
import { Directive, Input, OnDestroy } from '@angular/core';
import { MatAutocompleteTrigger } from '@angular/material/autocomplete';
@Directive({
selector: '[appAutocompletePosition]',
exportAs : 'appAutocompletePosition'
})
export class AutocompletePositionDirective implements OnDestroy {
public constructor(
private readonly matAutocompleteTrigger: MatAutocompleteTrigger,
) {
window.addEventListener('scroll', this.scrollEvent, true);
}
public ngOnDestroy(): void {
window.removeEventListener('scroll', this.scrollEvent, true);
}
private scrollEvent = (): void => {
if (this.matAutocompleteTrigger == null) {
return;
}
if (this.matAutocompleteTrigger.panelOpen) {
this.matAutocompleteTrigger.updatePosition();
}
}
}
Usage
<input type="text" matInput [matAutocomplete]="auto" #trigger="matAutocompleteTrigger" appAutocompletePosition="trigger" />