Our team is using the MatSnackBar of the Angular Material in the application. Because every one is in charge of different pages there are different durations times of the snackBars of each page. Some set the duration to 2000ms, others to 1000ms and some even made it 3000ms.
I want to get the duration value from a single variable so I can control the duration for all snackBars in one place. Maybe even to dismiss the developers from sending a duration value when calling the snackBar.open function.
this.snackBar.open(message, {
duration: 2000,
});
What is the best way for it?
You should set an application-wide default Snackbar configuration.
@NgModule({
providers: [
{provide: MAT_SNACK_BAR_DEFAULT_OPTIONS, useValue: {duration: 2500}}
]
})
You'll still need to scrub through your existing code and remove instances where an explicit duration is passed, but future code can just say this.snackbar.open(msg)
without any options.
I solved it by wrapping the MatSnackBar and using a factory for the dialog.open.
import { Injectable } from '@angular/core';
import { MatSnackBar, MatSnackBarConfig } from '@angular/material';
@Injectable()
export class SnackBarService {
private config: MatSnackBarConfig;
constructor(private snackBar: MatSnackBar) {
this.config = new MatSnackBarConfig();
this.config.duration = 2000;
}
public open(message: string, duration?: number, action?: string) {
this.config = duration ? Object.assign(this.config, { 'duration': duration }) : this.config;
this.snackBar.open(message, action, this.config);
}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With