如何在Angular2(Material2)中设置snack-bar的持续时间?

15

这个示例将永久停留在屏幕上:

snack-bar-demo.ts

import {Component, ViewContainerRef} from '@angular/core';
import {MdSnackBar, MdSnackBarConfig} from '@angular/material';

@Component({
  moduleId: module.id,
  selector: 'snack-bar-demo',
  templateUrl: 'snack-bar-demo.html',
})
export class SnackBarDemo {
  message: string = 'Snack Bar opened.';
  actionButtonLabel: string = 'Retry';
  action: boolean = false;

  constructor(
      public snackBar: MdSnackBar,
      public viewContainerRef: ViewContainerRef) { }

  open() {
    let config = new MdSnackBarConfig(this.viewContainerRef);
    this.snackBar.open(this.message, this.action && this.actionButtonLabel, config);
  }
}

如何让它在两秒后消失(设置持续时间/超时时间)?

5个回答

13

使用Angular Material 2.0.0-alpha.11版本,您现在可以为Snackbar添加超时时间。

open() {
    let config = new MdSnackBarConfig();
    config.duration = 10;
    this.snackBar.open("Message", "Action Label", config);
}

哇,你真快。我也想更新这个,只是在等发布 :) 谢谢。 - j809809jkdljfja

9

这应该可以工作。

open(msg,t=2000) {
        let config = new MdSnackBarConfig(this.viewContainerRef);
        let simpleSnackBarRef = this.snackBar.open(msg, 'ok, gotcha', config);
        setTimeout(simpleSnackBarRef.dismiss.bind(simpleSnackBarRef), t);
    }

这个可以工作。谢谢!!我只是想知道你是通过这种方式实现预期行为的,还是已经在 MdSnackBar 中按照此处描述的方式实现了某些功能: snack-bar
"它们通过被滑出屏幕或在超时后自动消失,或者在其他地方与用户交互(例如召唤新的表面或活动)而消失。"
- j809809jkdljfja
我认为目前没有这样的东西。如果您查看open方法,您将不会找到任何定时解雇程序。也就是说,snack-bar状态仍然是概念验证npm。他们可能/希望添加那些好东西,以更紧密地对齐您链接的预期设计规格。 - undefinederror

6
this._snackBar.open('Your Text','',
    { 
      duration: 2000
  });

4
持续时间可以通过可选的配置对象传递:
this.snackBar.open(
    this.message,
    this.action && this.actionButtonLabel, { 
        duration: 2000
    }
);

1
你可以这样做(Angular 8+)
openMessageSnackBar("Server error", "OK");

openMessageSnackBar(message: string, action: string) {
  this._snackBar.open(message, action, {
    horizontalPosition: "center",
    verticalPosition: "left",
    duration: 5000,
  });
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接