Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular-material MatSnackBar default duration time

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?

like image 813
Udi Mazor Avatar asked Dec 11 '22 08:12

Udi Mazor


2 Answers

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.

like image 96
Coderer Avatar answered Dec 24 '22 20:12

Coderer


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);
}}
like image 33
Udi Mazor Avatar answered Dec 24 '22 22:12

Udi Mazor