Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Snackbar - Global Duration Config

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!

like image 686
user2085143 Avatar asked Dec 20 '16 16:12

user2085143


2 Answers

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

like image 130
Mike Bovenlander Avatar answered Nov 10 '22 01:11

Mike Bovenlander


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);
    }
}
like image 35
aholtry Avatar answered Nov 10 '22 01:11

aholtry