How to Create a Custom Toastr Message Service in Angular

Are you tired of using third-party toastr message libraries in your Angular applications? Do you want to create a custom toastr message that perfectly fits your project requirements? In this blog post, we will show you how to create a custom service in Angular that implements a custom toastr message.

By the end of this blog post, you will have a fully functional custom toastr message service that you can use in your Angular applications. You will also have a solid understanding of how to create custom services in Angular and use Angular’s Dependency Injection mechanism.

So, whether you are a beginner or an experienced Angular developer, follow our step-by-step guide and create a custom toastr message service that meets your specific project requirements.

Demo

Create a Custom Toastr Message Service in Angular
Create a Custom Toastr Message Service in Angular

Demo

Here’s an example of how you can create a custom service in Angular that implements a custom toastr message

First, create a new service called ToastrService using the Angular CLI:

ng generate service Toastr

In your app.module.ts file, import the ToastrModule and add it to the imports array:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ToastrModule } from 'ngx-toastr';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    ToastrModule.forRoot()
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

In the toastr.service.ts file, import Injectable from @angular/core, and import the ToastrService from ngx-toastr.

import { Injectable } from '@angular/core';
import { ToastrService } from 'ngx-toastr';

@Injectable({ providedIn: 'root' })
export class CustomToastrService {
    constructor(private toastr: ToastrService) { }

    show(message: string, type: string, options?: any) {
        debugger;
        if (!options) {
            options = {
                timeOut: 5000,
                positionClass: 'toast-top-right',
                preventDuplicates: true,
                tapToDismiss: true
            };
        }

        switch (type) {
            case 'success':
                this.toastr.success(message, 'Success', options);
                break;
            case 'warning':
                this.toastr.warning(message, 'Warning', options);
                break;
            case 'error':
                this.toastr.error(message, 'Error', options);
                break;
            default:
                this.toastr.info(message, 'Info', options);
        }
    }

}

In this example, we’ve modified the show() method to use this.toastr instead of console.log(). We’re calling the success(), warning(), error(), or info() method on this.toastr based on the type parameter passed to the show() method. We’re also passing the message, title, and options parameters to the toastr method as needed.

Now you can use the CustomToastrService in any component by injecting it in the constructor:

import { Component } from '@angular/core';
import { CustomToastrService } from './custom-toastr.service';

@Component({
  selector: 'app-root',
  template: `
    <button (click)="showToastr()">Show Toastr</button>
  `
})
export class AppComponent {
  constructor(private toastr: CustomToastrService) {}

  showToastr() {
    this.toastr.show('This is a custom toastr message', 'success', { positionClass: 'toast-top-right' });
  }
}

What are all the possible options I can pass to this toast?

Here are some of the most commonly used options that you can pass to the toastr method:

  • closeButton: A boolean value that determines whether to display a close button on the toastr message. Default value is false.
  • debug: A boolean value that determines whether to enable debugging for the toastr message. Default value is false.
  • disableTimeOut: A boolean value that determines whether to disable the timeout for the toastr message. Default value is false.
  • enableHtml: A boolean value that determines whether to enable HTML content in the toastr message. Default value is false.
  • extendedTimeOut: A number value that determines the duration of the toastr message (in milliseconds) after the user hovers over the message. Default value is 1000.
  • messageClass: A string value that determines the CSS class for the toastr message.
  • onActivateTick: A boolean value that determines whether to activate a tick for the toastr message. Default value is false.
  • positionClass: A string value that determines the position of the toastr message on the screen. Possible values include toast-top-right, toast-bottom-right, toast-bottom-left, toast-top-left, toast-top-full-width, toast-bottom-full-width, toast-top-center, and toast-bottom-center.
  • preventDuplicates: A boolean value that determines whether to prevent duplicate messages from being displayed. Default value is false.
  • progressBar: A boolean value that determines whether to display a progress bar for the toastr message. Default value is false.
  • tapToDismiss: A boolean value that determines whether to dismiss the toastr message when the user clicks on it. Default value is true.
  • timeOut: A number value that determines the duration of the toastr message (in milliseconds) before it automatically disappears. Default value is 5000.
  • titleClass: A string value that determines the CSS class for the toastr message title.

These are just some of the most commonly used options. You can explore the ngx-toastr documentation to see all the available options and their descriptions.

Application Source Code @ LearnSmartCoding GitHub

Check out other topics that might interest you.

Leave a Reply

Your email address will not be published. Required fields are marked *

Verified by MonsterInsights