最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular 2 Snackbar - Global Duration Config - Stack Overflow

programmeradmin0浏览0评论

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 badges
Add a ment  | 

3 Answers 3

Reset to default 7

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 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 });
发布评论

评论列表(0)

  1. 暂无评论