How do I set a scroll strategy with MAT_DIALOG_SCROLL_STRATEGY

Viewed 2204

I want to set the scroll strategy for all dialogs in the project. I tested the behavior for one dialog with

@Component({
  selector: 'app-main',
  templateUrl: './main.component.html',
  styleUrls: ['./main.component.scss']
})
export class MainComponent {
    constructor(public dialog: MatDialog, private overlay: Overlay) {}

    showHelpDialog() {
        const dialogConfig = new MatDialogConfig();
        dialogConfig.scrollStrategy = this.overlay.scrollStrategies.noop();
        this.dialog.open(DialogComponent, dialogConfig);
    }
}

and it works as expected. On Angular Material I've read about the injection token MAT_DIALOG_SCROLL_STRATEGY. It probably should be something like:

@NgModule({
    /* ... */
    providers: [
        {
            provide: MAT_DIALOG_SCROLL_STRATEGY,
            useValue: /* ??? */
        }
    ]
})
export class AppModule { }

but I don't know how set the value. The scroll strategies can be found in @angular/cdk/overlay/scroll/scroll-stratey-options.ts in the class ScrollStrategyOptions but the member functions are non-static and I can't instantiate an object of ScrollStrategyOptions because I don't have the necessary constructor arguments. So basically I'm looking for a way to do something like

@NgModule({
    /* ... */
    providers: [
        {
            provide: MAT_DIALOG_SCROLL_STRATEGY,
            useValue: ScrollStrategyOptions.noop()
        }
    ]
})
export class AppModule { }

Here is an example project: stackblitz

1 Answers

You need to use a factory that accepts dependencies:

providers: [
    {
        provide: MAT_DIALOG_SCROLL_STRATEGY,
        useFactory: (scrollStrategyOptions: ScrollStrategyOptions) => scrollStrategyOptions.noop,
        deps: [ScrollStrategyOptions]
    }
]

The factory is called when MAT_DIALOG_SCROLL_STRATEGY is first requested. You define what dependencies the factory expects in the deps property.

Related