Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 524
j809809jkdljfja Avatar asked Oct 21 '16 20:10

j809809jkdljfja


People also ask

What is a snack bar in angular?

The <MatSnackBar>, an Angular Directive, is used to show a notification bar to show on mobile devices as an alternative of dialogs/popups.

How do you use MatSnackBar?

MatSnackBar is used to display information or text from bottom of the screen when performing any action. Approach: First, install the angular material using the above-mentioned command. After completing the installation, Import 'MatSnackBarModule' from '@angular/material/snack-bar' in the app.

What is snack bar UI?

Snackbars provide brief feedback about an operation through a message at the bottom of the screen. Snackbars contain a single line of text directly related to the operation performed. They may contain a text action, but no icons. Toasts (Android only) are primarily used for system messaging.

How do you close a snackbar mat?

A snackbar can be dismissed manually by calling the dismiss method on the MatSnackBarRef returned from the call to open . Only one snackbar can ever be opened at one time. If a new snackbar is opened while a previous message is still showing, the older message will be automatically dismissed.


2 Answers

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);
}
like image 68
Narendra CM Avatar answered Sep 18 '22 09:09

Narendra CM


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);
    }
like image 31
undefinederror Avatar answered Sep 19 '22 09:09

undefinederror