Angular 2 Snackbar - Global Duration Config

2k views Asked by At

I can set the duration of a snackbar message like so

let config = new MdSnackBarConfig();
config.duration = 5000;

this.snackBar.open(element.text, 'OK', config);

However I need to set the duration for multiple snackbars and would rather not have to pass in the config each time.

Can I somehow set a global duration config?

Thanks!

3

There are 3 answers

0
aholtry On

What we've done is included an external app.config.ts file at the module level and include it where we need it. This is an example of what's in the file.

export class Config {
    static apiUrl = "api/";
    static token = "";
    static snackBarDurration = 5000;
    ......
}

Then, all you have to do is declare it in your module and then import it in the component or service in which you want to use it. Here is an example.

import { Injectable } from "@angular/core";
import { Config } from "../../app.config";

@Injectable()
export class SnackBarService {

    .... // declare your snackbar here

    constructor() { }

    showSnackBar(elementText: string){
        let config = new MdSnackBarConfig();
        config.duration = Config.snackBarDurration; // Here is your change

        this.snackBar.open(elementText, 'OK', config);
    }
}
1
1323 On

I know it's not solution for a global configuration, but to make invocation more compact I declared config in params:

this.snackBar.open(elementText, 'OK', { duration: 3000 });
0
Mike Bovenlander On

I know this post is from a few years ago but for future reference i'm going to answer this anyway. Hoping I help someone who comes across this post like I did.

You can now inject the MatSnackBar with default options for modules by using the providers in your @NgModule:

import { MatSnackBarModule, MAT_SNACK_BAR_DEFAULT_OPTIONS } from '@angular/material';

@NgModule({
    declarations: [],
    imports: [
        MatSnackBarModule
    ],
    exports: [
        MatSnackBarModule
    ],
    providers: [
        { provide: MAT_SNACK_BAR_DEFAULT_OPTIONS, useValue: { duration: 2500 } }
    ]
})

Source: Material Angular doc's