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

In this tutorial we’ll cover how to implement a simple reusable alert notification module in Angular 10. The example includes just two pages, the first with a single alert and the second with multiple alerts displayed in two separate sections, and styling is done with bootstrap 4.5 css.

The example project code is available on GitHub at https://github.com/cornflourblue/angular-10-alert-notifications.

Here it is in action:

(See on StackBlitz at https://stackblitz.com/edit/angular-10-alerts)

Running the Angular 10 Alert Notifications Example Locally

  1. Install Node.js and npm from https://nodejs.org.
  2. Download or clone the tutorial project source code from https://github.com/cornflourblue/angular-10-alert-notifications.
  3. Install all required npm packages by running npm install or npm i 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 command line in the project root folder, this will build the application and automatically launch it in the browser on the URL http://localhost:4200.

NOTE: You can also start the app with the Angular CLI command ng serve --open. To do this first install the Angular CLI globally on your system with the command npm install -g @angular/cli.

For more info on setting up an Angular development environment see Angular - Setup Development Environment.

Adding Alerts to your Angular 10 App

To add alerts to your Angular application copy the /src/app/_alert folder from the example project into your 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.

#angular #angular 10

Angular 10 - Alert Notifications Example
79.85 GEEK