j809809jkdljfja
j809809jkdljfja

Reputation: 807

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)?

Upvotes: 15

Views: 11399

Answers (5)

aj_shela
aj_shela

Reputation: 377

You can do like this (angular 8+)

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

Upvotes: 1

BALU NANDAM
BALU NANDAM

Reputation: 71

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

Upvotes: 6

Kenton Lin
Kenton Lin

Reputation: 41

The duration can be pass via the optional configuration object:

this.snackBar.open(
    this.message,
    this.action && this.actionButtonLabel, { 
        duration: 2000
    }
);

Upvotes: 4

Narendra CM
Narendra CM

Reputation: 1426

With angular material 2.0.0-alpha.11, You can now add timeout to snackbar.

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

Upvotes: 13

undefinederror
undefinederror

Reputation: 861

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

Upvotes: 9

Related Questions