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!
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!
Share Improve this question asked Dec 20, 2016 at 16:27 user2085143user2085143 4,2327 gold badges42 silver badges71 bronze badges3 Answers
Reset to default 7I 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 es 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
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 ponent 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);
}
}
I know it's not solution for a global configuration, but to make invocation more pact I declared config in params:
this.snackBar.open(elementText, 'OK', { duration: 3000 });