angularmaterial-designsnackbarangular-material2angular2-material

How can I set duration of a snack-bar in angular2 (material2)


This example stays forever on the screen:

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);
  }
}

How can I make it disappear after 2 seconds (set duration/timeout somehow)?


Solution

  • this should work

    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);
        }