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)?
The <MatSnackBar>, an Angular Directive, is used to show a notification bar to show on mobile devices as an alternative of dialogs/popups.
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.
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.
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.
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);
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With