Angular Bootstrap alerts MDB Pro component
To improve the communication between your website/application and its users, you might want to consider adding some automatic pop-up messages.
With the right use of colors, they add some emotional weight to our information, ranging from a simple warning to critical system failure or from an operation success to a neutral information.
Toast service requires either
BrowserAnimationsModule
orNoopAnimationsModule
modules. Please import them to your app.module.ts.
Examples
Info message Warning message Success message Error message
Info message
Warning message
Success message
Error message
import { Component } from '@angular/core';
import { ToastService } from 'your_path_to/typescripts/pro';
@Component({
selector: 'toast-component-example',
templateUrl: 'toast.component.html',
})
export class ToastComponent {
constructor(private toastrService: ToastService) {}
showSuccess() {
this.toastrService.success('Info message');
}
showError() {
this.toastrService.error('Warning message');
}
showInfo() {
this.toastrService.info('Success message');
}
showWarning() {
this.toastrService.warning('Error message');
}
}
Important update!
Since version 4.3.7 , Toast Service has to be imported separately as singleton to avoid circular dependencies.
Import Toast Service as singleton:
app.module.ts
import { ToastModule } from 'ng-mdb-pro/pro/alerts';
...
imports: [
...
ToastModule.forRoot(),
...
],
app.component.ts
import {ToastService} from '../../typescripts/pro/alerts'
...
constructor(
...
private toast: ToastService
...
) { }
Sample usage:
ngOnInit() {
setTimeout(
() => this.toast.info("It works!")
);
}
Modifying opacity with toastClass
In some cases, you may want to change the default opacity value for each individual alert. To do this, use the toastClass option to assign a class containing the opacity styles.
Info message
Warning message
Success message
Error message
import { Component } from '@angular/core';
import { ToastService } from 'your_path_to/typescripts/pro';
@Component({
selector: 'toast-component-example',
templateUrl: 'toast.component.html',
})
export class ToastComponent {
constructor(private toastrService: ToastService) { }
showSuccess() {
const options = { toastClass: 'opacity' };
this.toastrService.success('Info message', options);
}
showError() {
const options = { toastClass: 'opacity' };
this.toastrService.error('Warning message', options);
}
showInfo() {
const options = { toastClass: 'opacity' };
this.toastrService.info('Success message', options);
}
showWarning() {
const options = { toastClass: 'opacity' };
this.toastrService.warning('Error message', options);
}
}
.opacity {
opacity: 1.0 !important;
}
Showing alerts after server call
If you are in contact with a server, it may be useful to display alerts to the user on whether the data has been successfully downloaded or not. The following example illustrates the basic use of alerts in a server contact.
Users:
- {{ user }}
import { Http } from '@angular/http';
import { ToastService } from 'ng-uikit-pro-standard/pro/alerts/toast/toast.service';
import { Component, AfterViewInit } from '@angular/core';
@Component({
selector: 'server-alerts',
templateUrl: './server-alerts.component.html',
styleUrls: ['./server-alerts.component.scss'],
})
export class ServerAlertsComponent implements AfterViewInit {
url: string = 'https://jsonplaceholder.typicode.com/users/';
usersArray: Array = [];
constructor(private toastrService: ToastService, private http: Http) { }
showSuccess(data: any) {
this.toastrService.success('User: ' + '"' + data.name + '"' + ' successfully fetched');
}
showError(id: number) {
this.toastrService.error("Error: User with ID: " + id + " doesn't exists");
}
connectionEnd(id: number) {
this.toastrService.error('Connection ended after ' + id + ' calls');
}
getData(id: number) {
return this.http.get(this.url + id);
}
ngAfterViewInit() {
let i = 1;
const getDataInterval = setInterval(() => {
this.getData(i).subscribe((response: any) => {
response = response.json();
this.usersArray.push(response.name);
this.showSuccess(response);
i++;
}, error => {
if (i < 15) {
this.showError(i);
} else {
clearInterval(getDataInterval);
this.connectionEnd(i);
}
i++;
});
}, 2000);
}
}
Options
There's global options and individual toast options. All individual toast options are included in the global options. See file toastr-config.ts The toastComponent can be inherited and modified.
Global options for alerts need to be set in
ToastModule.forRoot({})
in
imports: []
array located in
app.module.ts
For example, global options that allows only 2 alerts be visible at time should looks in this way:
ToastModule.forRoot({maxOpened: 2})
ToastrConfig (Global Options)
Name | Default | Description |
---|---|---|
maxOpened: number | 0 | max toasts opened; toasts will be queued |
autoDismiss: boolean | false | dismiss current toast when max is reached |
iconClasses | error: 'toast-error', info: 'toast-info', success: 'toast-success', warning: 'toast-warning' | classes used on toastr service methods |
newestOnTop: boolean | true | new toast placement |
preventDuplicates: boolean | false | block duplicate messages |
ToastConfig (Individual Toast options)
Name | Default | Description |
---|---|---|
actionButoon: string | empty string | show action button with specified title |
closeButton: boolean | false | show close button |
timeOut: number | 5000 | time to live |
enableHtml: boolean | false | allow html in message; (UNSAFE) |
extendedTimeOut: number | 1000 | time to close after a user hovers over toast |
progressBar: boolean | false | show progress bar |
toastClass: string | 'toast' | class on toast. Note that if you want to add your custom class, you have to put it in your's
global stylesheet -
styles.scss
|
positionClass: string | 'toast-top-right' | class on toast |
titleClass: string | 'toast-title' | class inside toast on title |
messageClass: string | 'toast-message' | class inside toast on message |
tapToDismiss: boolean | true | close on click |
Example:
showSuccess(){
const options = { closeButton: true, actionButton: 'Action', tapToDismiss: false, titleClass: 'yellow' };
this.toastrService.success('Hello world!', 'Toastr success!', options);
}
showError() {
const options = { enableHtml: false, positionClass: 'toast-bottom-right' };
this.toastrService.error('Error message', 'Toastr error!', options);
}
showInfo() {
const options = { extendedTimeOut: 30000, messageClass: 'pink' };
this.toastrService.info('Info message', 'Toastr info!', options);
}
showWarning() {
const options = { progressBar: true, timeOut: 3000, toastClass: 'black'};
this.toastrService.warning('Warnig message', 'Toastr warning!', options);
}
Events
Here you can find events which are fired by Toast Service
Name | Usage | Description |
---|---|---|
onAction | alertInstance.onAction.subscribe(() => {}) | The event is fired when action button is clicked |
onTap | alertInstance.onTap.subscribe(() => {}) | The event is fired when tap on the alert is detected. |
onShown | alertInstance.onShown.subscribe(() => {}) | The event is fired when alert shows on screen |
onHidden | alertInstance.onHidden.subscribe(() => {}) | The event is fired when alert dissapears from screen |
Example:
showSuccess() {
const options = { closeButton: true, progressBar: true, actionButton: 'Action', tapToDismiss: true};
const alertInstance = this.toastrService.success('Hello world!', 'Toastr success!', options);
alertInstance.onAction.subscribe(() => {
console.log('on action');
});
alertInstance.onTap.subscribe(() => {
console.log('on tap');
});
alertInstance.onShown.subscribe(() => {
console.log('on shown');
});
alertInstance.onHidden.subscribe(() => {
console.log('on hidden');
});
}
API Reference:
In order to speed up your application, you can choose to import only the modules you actually need, instead of importing the entire MDB Angular library. Remember that importing the entire library, and immediately afterwards a specific module, is bad practice, and can cause application errors.
API Reference for MDB Angular Toasts:
// For MDB Angular Pro
import { ToastModule, WavesModule } from 'ng-uikit-pro-standard'
// Angular Animations Module
import { BrowserAnimationsModule } from '@angular/platform-browser/animations'