Showing Proper Messages In Angular Using Ngx-toastr

Introduction

In an Angular project, we need to show messages on every success, error, warning, information to the user. Displaying proper messages enhance application performance and user-interaction. Suppose we have a creation page where the user has filled a form and submitted it. If the server crashes or gives some unexpected error, the proper message should be shown on the screen to the user. If we will not show a proper error message, the user will not know and might understand that it is a success. Showing notifications plays a major part in designing any application. Now we will see how we can show different error, success, warning and info messages using ngx-toastr

Installing ngx-toastr

We will install the module using the NPM command and we will save the package in the package.json file as well using --save option:

npm install ngx-toastr --save

Install animations package as well to make toaster display with animations properly:

npm install @angular/animations --save

We need to import the ToastrModule and BrowserAnimationsModule in our project. Make an entry in the app.module.ts file in the imports array as follows:

import { CommonModule } from '@angular/common';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ToastrModule } from 'ngx-toastr';
 
@NgModule({
  imports: [
    CommonModule,
    BrowserAnimationsModule, // Animations module added
    ToastrModule.forRoot() // ToastrModule added
  ],
  bootstrap:  [AppComponent],
  declarations: [AppComponent]
})
export class AppModule {}

Adding CSS

Add the following style in the angular-cli.json file:

    "styles": [
      "../node_modules/bootstrap/dist/css/bootstrap.min.css",
          "styles.scss",
         "../node_modules/ngx-toastr/toastr.css"
    ],

Now we will create a service util.service.ts file where we will write different functions for success, error, warning and info toaster messages. We will use individual options timeout, enableHtml, toastClass, closeButton, etc according to our requirement. We are passing different parameters to the show() method which has the following signature. We have used this method to override the default toaster functionality. 

ToastrService.show(message?: string, title?: string, override?: Partial<IndividualConfig>, type?: string): ActiveToast

Now we have used toastClass as toastr-class-success, toastr-class-info, toastr-class-warning, toastr-class-error with respect to our specific error message. 

import { ToastrService } from 'ngx-toastr';
export class UtilService {

  constructor(
    private toastr: ToastrService) {


   public showToastrSuccess(title: string, description: string) {
    let successMessage = '<div class="toastr-success"></div><div class="toastr-description">' + description + '</div>';
    this.toastr.show(successMessage, title, {
      enableHtml: true,
      closeButton: true,
      timeOut: 5000,
      positionClass: 'toast-top-center',
      toastClass: 'toastr-class-success toast'
    });
  }

  public showToastrInfo(title: string, description: string) {
    let infoMessage = '<div class="toastr-info"></div><div class="toastr-description">' + description + '</div>';
    this.toastr.show(infoMessage, title, {
      enableHtml: true,
      closeButton: true,
      timeOut: 5000,
      positionClass: 'toast-top-center',
      toastClass: 'toastr-class-info toast'
    });
  }

  public showToastrWarning(title: string, description: string) {
    let warningMessage = '<div class="toastr-warning"></div><div class="toastr-description">' + description + '</div>';
    this.toastr.show(warningMessage, title, {
      enableHtml: true,
      closeButton: true,
      timeOut: 5000,
      positionClass: 'toast-top-center',
      toastClass: 'toastr-class-warning toast'
    });
  }

  public showToastrError(title: string, description: string) {
    let errorMessage = '<div class="toastr-error"></div><div class="toastr-description">' + description + '</div>';
    this.toastr.show(errorMessage, title, {
      enableHtml: true,
      closeButton: true,
      timeOut: 5000,
      positionClass: 'toast-top-center',
      toastClass: 'toastr-class-error toast'
    });
  }
}

Usage

Now we will call these methods in our component.ts files whenever we need to show messages.
On successfully doing some action like creation, deletion, updating, etc we will show success toaster message as follows. 

   async deleteUser(parent) {
    if (parent) {
      if (this.utilSrv.showDeleteConfirmDialog({ title: "Delete", message: "Are you sure to delete user?'"})) {
        await this.adminSrv.deleteUser(id);
        this._utilService.showToastrSuccess('Parent Deleted', 'Parent deleted successfully.'); // Usage
      }
    }
  }

We will show warning messages using our warning method whenever we need to warn the user after performing some actions.

saveUser() {
    if (this.user && this.user.name && this.contact.email) {
      this._contactService.checkDuplicateUser(this.contact.email)
        .then((res: boolean) => {
          let isDuplicateEmail = res;
          if (isDuplicateEmail == true) {
            this._utilityService.showToastrWarning('Warning', 'The user already exists!');
           }
}      

We will show error messages when some action got failed.

 this.adminSrv.deleteUser(id)
            .then(res => {
              if (res) {
                this._utilityService.showToastrSuccess('Deleted', 'Deleted successfully.');           
            }
            })
            .catch(err => {
              this._utilityService.showToastrError('Error', 'Error on deleting user!');
             })
        }

Comments