How to Create Alert (Toaster) Notifications with Angular 8

How to Create Alert (Toaster) Notifications with Angular 8

In this article shows how to implement a simple reusable alert / toaster notification module in Angular 8

Alert messages (a.k.a. toaster notifications) are an extremely common requirement in web applications for displaying status messages to the user e.g. error, success, warning and info alerts.

The example has two pages, one with a single alert and the other with multiple alerts displayed in separate sections.

Running the Angular 8 Alert / Toaster Example Locally
  1. Install NodeJS and NPM from https://nodejs.org/en/download/.
  2. Download or clone the tutorial project source code from https://github.com/cornflourblue/angular-8-alert-notifications.
  3. Install all required npm packages by running npm install from the command line in the project root folder (where the package.json is located).
  4. Start the application by running npm start from the
  5. command line in the project root folder, this will build the application
  6. and automatically launch it in the browser on the URL
  7. http://localhost:8080.
Adding Alerts / Toaster Notifications to Your Angular 8 App

To add alerts to your Angular 8 application you'll need to copy the /src/app/_alert folder and contents from the example project, the folder contains the alert module and associated files, including:

  • alert.component.html - alert component template that contains the html for displaying alerts.
  • alert.component.ts - alert component with the logic for displaying alerts.
  • alert.model.ts - alert model class that defines the properties of an alert, it also includes the AlertType enum that defines the different types of alerts.
  • alert.module.ts - alert module that encapsulates the alert component so it can be imported by the app module.
  • alert.service.ts - alert service that can be used by any angular component or service to send alerts to alert components.
  • index.ts - barrel file that re-exports the alert module, service and model so they can be imported using only the folder path instead of the full path to each file, and also enables importing from multiple files with a single import.

Import the Alert Module into your App Module

To make the alert component available to your Angular 8 application you need to add the AlertModule to the imports array of your App Module (app.module.ts). See the app module from the example app below, the alert module is imported on line 4 and added to the imports array of the app module on line 14.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AlertModule } from './_alert';
import { appRoutingModule } from './app.routing';

import { AppComponent } from './app.component';
import { HomeComponent } from './home';
import { MultiAlertsComponent } from './multi-alerts';

@NgModule({
    imports: [
        BrowserModule,
        AlertModule,
        appRoutingModule
    ],
    declarations: [
        AppComponent,
        HomeComponent,
        MultiAlertsComponent
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

Add the tag where you want alerts to be displayed

Add the alert component tag wherever you want alert messages to be displayed. The alert component accepts an optional id attribute if you want to display multiple alerts in different locations (see the Multiple Alerts page in the example above). An alert component instance with an id will display any messages sent to the alert service with the same alertId specified, e.g. alertService.error('something broke!', 'alert-1'); will send an error message to the alert component with id="alert-1".

The app component template in the example /src/app/app.component.html contains a global alert tag without an id above the router-outlet tag, this alert instance displays any messages sent to the alert service without an alertId specified, e.g. alertService.success('you won!'); will send a success message to the global alert without an id.



    
        
        
    

Displaying Alert / Toaster Notifications in Your Angular 8 App

Once you've added support for alerts / toaster notifications to your app by following the previous steps, you can trigger alert notifications from any component in your application by simply injecting the alert service and calling one of it's methods for displaying different types of alerts: success(), error(), info() and warn().

Here is the home component from the example app that contains methods that pass example notification messages to the alert service when each of the buttons is clicked. In a real world application alert notifications can be triggered by any type of event, for example an error from an http request or a success message after a user profile is saved.

import { Component } from '@angular/core';

import { AlertService } from '../_alert';

@Component({ templateUrl: 'home.component.html' })
export class HomeComponent {
    constructor(private alertService: AlertService) { }

    success(message: string) {
        this.alertService.success(message);
    }

    error(message: string) {
        this.alertService.error(message);
    }

    info(message: string) {
        this.alertService.info(message);
    }

    warn(message: string) {
        this.alertService.warn(message);
    }

    clear() {
        this.alertService.clear();
    }
}

And here is the home component template containing the buttons that are bound to the above methods.

# Angular 8 Alerts

Success
Error
Info
Warn
Clear
Breakdown of the Angular 8 Alert / Toaster Notification Code

Below is a breakdown of the pieces of code used to implement the alert / toaster notification example in Angular 8, you don't need to know the details of how it all works to use the alerts in your project, it's only if you're interested in the nuts and bolts or if you want to modify the code or behaviour.

import { Injectable } from '@angular/core';
import { Router, NavigationStart } from '@angular/router';
import { Observable, Subject } from 'rxjs';
import { filter } from 'rxjs/operators';

import { Alert, AlertType } from './alert.model';

@Injectable({ providedIn: 'root' })
export class AlertService {
    private subject = new Subject();
    private keepAfterRouteChange = false;

    constructor(private router: Router) {
        // clear alert messages on route change unless 'keepAfterRouteChange' flag is true
        this.router.events.subscribe(event => {
            if (event instanceof NavigationStart) {
                if (this.keepAfterRouteChange) {
                    // only keep for a single route change
                    this.keepAfterRouteChange = false;
                } else {
                    // clear alert messages
                    this.clear();
                }
            }
        });
    }

    // enable subscribing to alerts observable
    onAlert(alertId?: string): Observable {
        return this.subject.asObservable().pipe(filter(x => x && x.alertId === alertId));
    }

    // convenience methods
    success(message: string, alertId?: string) {
        this.alert(new Alert({ message, type: AlertType.Success, alertId }));
    }

    error(message: string, alertId?: string) {
        this.alert(new Alert({ message, type: AlertType.Error, alertId }));
    }

    info(message: string, alertId?: string) {
        this.alert(new Alert({ message, type: AlertType.Info, alertId }));
    }

    warn(message: string, alertId?: string) {
        this.alert(new Alert({ message, type: AlertType.Warning, alertId }));
    }

    // main alert method    
    alert(alert: Alert) {
        this.keepAfterRouteChange = alert.keepAfterRouteChange;
        this.subject.next(alert);
    }

    // clear alerts
    clear(alertId?: string) {
        this.subject.next(new Alert({ alertId }));
    }
}
Angular 8 Alert Service

The alert service (/src/app/_alert/alert.service.ts) acts as the bridge between any component in an Angular application and the alert component that actually displays the alert / toaster messages. It contains methods for sending and clearing alert messages, it also subscribes to the router NavigationStart event to automatically clear alert messages on route change, unless the keepAfterRouteChange flag is set to true, in which case the alert messages survive a single route change and are cleared on the next route change.

The service uses the RxJS Observable and Subject classes to enable communication with other components.

import { Injectable } from '@angular/core';
import { Router, NavigationStart } from '@angular/router';
import { Observable, Subject } from 'rxjs';
import { filter } from 'rxjs/operators';

import { Alert, AlertType } from './alert.model';

@Injectable({ providedIn: 'root' })
export class AlertService {
    private subject = new Subject();
    private keepAfterRouteChange = false;

    constructor(private router: Router) {
        // clear alert messages on route change unless 'keepAfterRouteChange' flag is true
        this.router.events.subscribe(event => {
            if (event instanceof NavigationStart) {
                if (this.keepAfterRouteChange) {
                    // only keep for a single route change
                    this.keepAfterRouteChange = false;
                } else {
                    // clear alert messages
                    this.clear();
                }
            }
        });
    }

    // enable subscribing to alerts observable
    onAlert(alertId?: string): Observable {
        return this.subject.asObservable().pipe(filter(x => x && x.alertId === alertId));
    }

    // convenience methods
    success(message: string, alertId?: string) {
        this.alert(new Alert({ message, type: AlertType.Success, alertId }));
    }

    error(message: string, alertId?: string) {
        this.alert(new Alert({ message, type: AlertType.Error, alertId }));
    }

    info(message: string, alertId?: string) {
        this.alert(new Alert({ message, type: AlertType.Info, alertId }));
    }

    warn(message: string, alertId?: string) {
        this.alert(new Alert({ message, type: AlertType.Warning, alertId }));
    }

    // main alert method    
    alert(alert: Alert) {
        this.keepAfterRouteChange = alert.keepAfterRouteChange;
        this.subject.next(alert);
    }

    // clear alerts
    clear(alertId?: string) {
        this.subject.next(new Alert({ alertId }));
    }
}
Angular 8 Alert Component

The alert component (/src/app/_alert/alert.component.ts) controls the adding & removing of alerts in the UI, it maintains an array of alerts that are rendered by the component template.

The ngOnInit method subscribes to the observable returned from the alertService.onAlert() method, this enables the alert component to be notified whenever an alert message is sent to the alert service and add it to the alerts array for display. Sending an alert with an empty message to the alert service tells the alert component to clear the alerts array.

The ngOnDestroy() method unsubscribes from the alert service when the component is destroyed to prevent memory leaks from orphaned subscriptions.

The removeAlert() method removes the specified alert object from the array, it allows individual alerts to be closed in the UI.

The cssClass() method returns a corresponding bootstrap alert class for each of the alert types, if you're using something other than bootstrap you can change the CSS classes returned to suit your application.

import { Component, OnInit, OnDestroy, Input } from '@angular/core';
import { Subscription } from 'rxjs';

import { Alert, AlertType } from './alert.model';
import { AlertService } from './alert.service';

@Component({ selector: 'alert', templateUrl: 'alert.component.html' })
export class AlertComponent implements OnInit, OnDestroy {
    @Input() id: string;

    alerts: Alert[] = [];
    subscription: Subscription;

    constructor(private alertService: AlertService) { }

    ngOnInit() {
        this.subscription = this.alertService.onAlert(this.id)
            .subscribe(alert => {
                if (!alert.message) {
                    // clear alerts when an empty alert is received
                    this.alerts = [];
                    return;
                }

                // add alert to array
                this.alerts.push(alert);
            });
    }

    ngOnDestroy() {
        // unsubscribe to avoid memory leaks
        this.subscription.unsubscribe();
    }

    removeAlert(alert: Alert) {
        // remove specified alert from array
        this.alerts = this.alerts.filter(x => x !== alert);
    }

    cssClass(alert: Alert) {
        if (!alert) {
            return;
        }

        // return css class based on alert type
        switch (alert.type) {
            case AlertType.Success:
                return 'alert alert-success';
            case AlertType.Error:
                return 'alert alert-danger';
            case AlertType.Info:
                return 'alert alert-info';
            case AlertType.Warning:
                return 'alert alert-warning';
        }
    }
}
Angular 8 Alert Component Template

The alert component template (/src/app/_alert/alert.component.html) renders an alert message for each alert in the alerts array using the Angular *ngFor directive.

Bootstrap 4 is used for styling the alerts / toaster notifications in the example, you can change the HTML and CSS classes in this template to suit your application if you're not using Bootstrap.


    {{alert.message}}
    ×

Angular 8 Alert Model and Alert Type Enum

The Alert model (/src/app/_alert/alert.model.ts) defines the properties of each alert object, and the AlertType enum defines the types of alerts allowed in the application.

export class Alert {
    type: AlertType;
    message: string;
    alertId: string;
    keepAfterRouteChange: boolean;

    constructor(init?:Partial) {
        Object.assign(this, init);
    }
}

export enum AlertType {
    Success,
    Error,
    Info,
    Warning
}
Angular 8 Alert Module

The AlertModule (/src/app/_alert/alert.module.ts) encapsulates the alert component so it can be imported and used by other Angular modules.

Important reasons for developers to adopt Angular JS development

 Important reasons for developers to adopt Angular JS development

In the current scenarios, e-commerce companies are very keen to create an online impact. The web and app development market are at its peak of popularity. There is a high demand for web and app developers with a growing number of websites. Angular...

In the current scenarios, e-commerce companies are very keen to create an online impact. The web and app development market are at its peak of popularity. There is a high demand for web and app developers with a growing number of websites. Angular has been a top choice for web development and it's the latest version AngularJS has gained popularity in the industry. This java script framework has created its prominent position in creating web apps.
Regardless of whether there are numerous different systems accessible for web development, AngularJS can support among them all. Since its introduction in the market, Angular has been creating waves in the market.

Introduction

Angular js is a powerful framework that was developed by Google. It is used to build dynamic apps with power-packed features. It was first introduced in 2010 and created by developers at Google. This framework was created to simplify and remove the challenges in creating dynamic apps. It uses HTML, CSS, and java script to create dynamic single-page applications. Angular Js is inclusive of Mongo DB and it is a frontend fragment of Mean Stack. In the developer's community, Angular is considered as a reliable and fast Java script framework. Many popular apps like PayPal. You tube, Netflix, the guardian, Lego are built using the AngularJS framework.

In this blog, we are listing some compelling reasons to pick angular development to familiarize you with its potential

• Open-source framework: It is not a library but open-source frameworks that enable the developers to build well-performing single page web applications. Just after its launch, it became hugely popular among the developers and it is not going to come at a halt.

• Simplified MVC structure: Developers use AngularJS to build robust and interactive web applications. AngularJS framework uses MVC architecture to create interactive applications. AngularJS makes it easy for developers to create apps as they are only required to split the applications.

• Extensive community: As angular is built by Google, it is backed by a very large community of professionals. The Angular JS conferences of the professionals are held all over the world. Hackathons are also organized in IT communities that include some professional and skilled engineers who can help with the queries and questions related to Angular.

• Declarative code system: In Angular JS developers can create declarative patterns by using declarative paradigms. It enables developers to be less heavy, and easy to read. In this framework, the developers get data models that are not too complex to write that abolishes the need to use any getter/setters and with easy data manipulation.

• Two-way data binding: It is one of the impeccable features that makes Angularjs popular in the developers' community. It allows seamless projections of the models and data binding. In this framework, any changes in the user interface make an impact on the application objects. The developers are not required to fresh the cycle and that makes it vulnerable to bugs.

• Using directives: AngularJS makes use of Directives as the developers can build custom HTML tags that function as custom widgets and it can be possible using directives. Its implications are also in the case of the use of decorating components and manipulation of DOM elements in appealing ways.

• Enterprise-level testing: When using Angular JS there is no need for demanding any other supplementary framework or additional plugins. In the process, parts of applications are put in the angular framework which is not too complex for manipulation. In module separation, developers can load essential services in an effective way for the performance of automatic testing.

• Client-side situation: AngularJS mainly works at the client-side and it is fully compatible with both web and mobile browsers. It can function with any projects without the need for any backend notifications. The developers can easily use AngularJS for the front end of applications.

• Easy to use: AngularJS is rich with its features and facilitates developers to reduce any need for writing codes. It reduces the burden of developers by the application of MVC architecture and data models.

Many other significant features make AngularJS prioritize by the developers than other Javascript frameworks. The above-mentioned reasons have made it the top choice for reputed companies all across the globe for web development. Developers at the company master the skills to work with Angular JS development for web. The company is equipped with dedicated professionals having sound technical knowledge of working with AngularJS. We offer offshore services to extend our reach all across the globe with various models. We have more than 15 years of experience in the industry that we use to deliver high-quality solutions by leveraging the latest technology and quality standards.

Mobile App Development Company India | Ecommerce Web Development Company India

Mobile App Development Company India | Ecommerce Web Development Company India

Best Mobile App Development Company India, WebClues Global is one of the leading web and mobile app development company. Our team offers complete IT solutions including Cross-Platform App Development, CMS & E-Commerce, and UI/UX Design.

We are custom eCommerce Development Company working with all types of industry verticals and providing them end-to-end solutions for their eCommerce store development.

Know more about Top E-Commerce Web Development Company

Hire PHP Developer and Web Developer for your Online Business

Hire PHP Developer and Web Developer for your Online Business

PHP is widely used open-source scripting language it helps in making dynamically easy your websites and web application. Mobiweb Technology is your best technical partner and offering you solution for any kind of website and application...

PHP is widely used open-source scripting language it helps in making dynamically easy your websites and web application. Mobiweb Technology is your best technical partner and offering you solution for any kind of website and application development. To hire PHP developer and web developer at affordable prices contact Mobiweb Technology via [email protected]