Home » Angular » How to create alerts in Angular Quickly

How to create alerts in Angular Quickly

In this tutorial, I will show how to create a reusable alert in Angular 5. I assume that you are familiar with Angular basics and RXJS library. If you want to follow the video tutorial, see this video on my YouTube channel.

Notice: Please go to YouTube and watch this video because sometimes you might not be able to see this video in full screen on this website. Also, don’t forget to subscribe.

I outlined steps that we will follow in this tutorial. After creating your own alert module, you can use it again and again in your application to keep the consistency. 

1. Create a new Angular application.

2. Create an alert module.

3. Create an alert interface.

4. Create an alert service.

5. Create an alert component.

6. Create the markup and the styles.

7. Use the alert service.

So, let’s start!

01. Create a new Angular application 

The first step is creating a new Angular application. In this tutorial, I’m going to use  Angular version 5.0. It is not a matter. There are small differences among different Angular versions except Angular js.   If you want to know how to create a fresh Angular application, please read this tutorial by following the link here.

Notice:

01. If you want to integrate this alert service into your existing project, you don’t need to create a new application

02. You don’t need to follow the exact folder structure of this tutorial. Also, you can use any name for your modules, services etc.

02. Create an alert module in the Angular application

Navigate to project folder and open command prompt. Then, type “ng g m shared/modules/alert”. 

ng g m shared/modules/alert

As a result, you can see the new Angular module (alert.module.ts) inside the src/app/shared/modules/alert folder. Then, create a new file call, index.ts inside the modules folder and add this piece of code. The index.ts file helps to import files and keep the reusability of each file. 

export * from './alert/alert.module';

Similarly, create another file called, index.ts in the shared folder and add this piece of code.

export * from './modules';

Then, import the alert module into the app module (or you can import the alert module into an appropriate level in your application). After importing the module, the code in the app module is as follows.

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


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


@NgModule({
  declarations: [
    AppComponent,
    TestComponent
  ],
  imports: [
    BrowserModule,
    AlertModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

3. Create an alert interface in the Angular application

The next step is creating an alert interface. So, to create it, type “ng g interface shared/modules/alert/interfaces/alert” and hit enter. Here g stand for generate.

ng g interface shared/modules/alert/interfaces/alert

As a result, you can see the new interface file inside the src/app/shared/modules/interfaces folder. Then, open alert.interface.ts and add the following code.

export interface Alert {
  title: string; //title in our alert window.
  type: string;  //type if our alert. It may be 'success, danger, infor'
  time:number;   //life time of alert
  body:string;   // Message that we want to show in alert
}

You can specify more properties according to your requirements.

4. Create an alert Service in the Angular application

The fourth step is creating an alert service. To do that, type “ng g s shared/modules/alert/services/alert” on cmd and git enter. Here g stand for generate and s stand for service.

ng g s shared/modules/alert/services/alert

As a result, you can see two files inside the src/app/shared/modules/alert/services folder. Open the alert.service.ts file and add the following code.

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';

//this is alert-emit interface
import { Alert } from '../interfaces/alert'; 


@Injectable()
export class AlertService {

  alertSettings$ = new Subject<Alert>()

  constructor() { }


  create(
  	title: string, type: string , time: number, body: string){
  	this.alertSettings$.next({
  		title,
  		type,
  		time,
  		body
  	});
  }

}

This alert service will make communication among components.

5. Create an alert component in Angular application

As the next step, create an alert component for the application.

To do that type, “ng g c shared/modules/alert” in the console and hit enter.

ng g c shared/modules/alert

It will give the alert.component.ts file inside the src/app/shared/modules/alert folder. Don’t worry about the other files.

Notice: This command automatically imports our alert component into the alert module. So, you don’t need to import it manually.

Then, open the alert.module.ts and import the alert service. After that, the code in the alert.module.ts file is as follows.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angulOar/common';
import { AlertComponent } from './alert.component';
import { AlertService } from './services/alert.service';

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [AlertComponent],
  exports: [AlertComponent], //this is  very important
  providers: [AlertService]

})
export class AlertModule { }


Then, open the alert.component.module and create your logic according to your requirements to handle the alert. After doing that, the code in the alert.component.ts file is as follows.

import { Component, OnInit, NgZone } from '@angular/core';
import{ trigger, transition, style, state, animate  } from '@angular/animations';
import { AlertService } from './services/alert.service';

@Component({
  selector: 'app-alert',
  templateUrl: './alert.component.html',
  styleUrls: ['./alert.component.scss'],
  animations: [
  trigger('dialog', [
      transition('void => *', [
        style({transform: 'scale3d(.3, .3, .3)'} ),
        animate(100)
        ]),
      transition('void => *', 
        animate(100, style({transform: 'scale3d(.3, .3, .3)'})))
    ])
  ]
})
export class AlertComponent implements OnInit {

  //hide and show alert
  modalStatus : boolean;

  //custom settings
  title:string;
  type: string;
  time: number;
  body: string;

  //default settings
  color: string;
  backColor: string;

  constructor(
  	private alertService : AlertService,
  	private _ngZone : NgZone
  	) { }

  ngOnInit() {

  	this.alertService.alertSettings$.subscribe(
  		(data) => {
 			
 			this.title = data.title;
 			this.type = data.type;
 			this.time = data.time;
 			this.body = data.body

 			if(this.type == "danger"){
 				this.backColor = "#dc3545";
 			}

 			if(this.type == "infor" ){
 				this.backColor = "#117a8b";
 			}

 			if(this.type == "success"){
 				this.backColor = "#28a745";
 			}

 			//show alert
 			this.modalStatus = true;

            // hide alert after given time
 			this._ngZone.runOutsideAngular(() =>

 				setTimeout(() =>
 					this._ngZone.run(() => 
 						this.modalStatus = false
 						), this.time
 					)
 				)

  		}
  		);

  }

  //close alert afert click on ok and cross
  resolve(){
  	this.modalStatus = false;
  }

}

6. Create markup and styles in the Angular application

This is the time to create a markup(html code) for the alerts component in the Angular application.

So, open the alert.component.ts file and type the HTML code for the alert component. Here, you can change the appearance of your alter. After creating the structure of the appearance of the alter, the code in the alert.component.html file is as follows.

<!-- The Modal -->
<div id="myModal" class="modal" *ngIf="modalStatus" >
  <!-- Modal content -->
  <div class="modal-content" [@dialog] >
  	<div class="header" [style.background-color]="backColor">
  	    <h3 >{{title}}</h3>
  		<span class="close" (click)="resolve()">×</span>
  	</div>

  	<div class="body">
  		<p>{{body}}</p>
  		<hr>
  	</div>

  	<div class="footer">
  		
  		<span class="footer-btn">
  			
  			<button class="btn btn-default" (click)="resolve()">OK</button>
  		</span>
  	</div>
  </div>
  
</div>

Then, open alert.component.scss and create styles for alerts. I added some styles to my alert as following code.

.modal {
    
    display: block;
    position: fixed; /* Stay in place */
    z-index: 1031; /* Sit on top */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content/Box */
.modal-content {
    background-color: #fefefe;
    margin: 15% auto; /* 15% from the top and centered */
    padding: 0px;
    border: 1px solid #888;
    width: 30%; /* Could be more or less, depending on screen size */
}

/* The Close Button */
.close {
    color: #aaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
    padding-top: 0.5rem;
    padding-right: 0.5rem;   
}

.header{

    background-color: #bd2130;

}

.close:hover,
.close:focus {
    color: black;
    text-decoration: none;
    cursor: pointer;
}

.body{
    text-align: center;
    padding-top: 2.2rem;
}

.footer-btn{
    float: right;
    padding-bottom: 20px;
    padding-right: 20px;
}

h3 {
    float: left;
    padding-top: 0.5rem;
    padding-left: 0.5rem;
    color: #fff;   
}

The “app-alert” selector in the alert.component.ts file should put into app.component.html because Angular uses only one HTML file to run the entire application. After adding the selector, the code in the app.component.html is as follows.

Note: This step is very important.

<app-alert></app-alert>

Then, import the BrowserAnimationModule into the app.module.ts. So, the code in the app.module.ts file is as follows.

import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NgModule } from '@angular/core';
import { AlertModule } from './shared'


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


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

Finally, we have to add bootstrap (or any of your UI library) into the application. To do that, Open index.html file and add the following code.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384 Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

Now your alert service is ready to use. However, let me show you how to use it in your project. Also, you can configure the alert service according to your requirements.

7. Use the alert service

Notice: Bellow steps are not compulsory. I will do those steps because I want to show you how to use this alert service in the project.

Assume that there is another component called test.component.ts in our application and we want to use the alert service inside that component. Also, assume there is a method call triggerAlert() in test.component.ts.

So, we have to complete following these steps to use the alert service in our test component.

01. Import the alert service into the test.component.ts.

02. Use create method that we defined in alert.serivce.ts

Finally, the code in the test.component.ts is as follows.

import { Component, OnInit } from '@angular/core';
import { AlertService } from '../shared/modules/alert/services/alert.service';
@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {

  constructor(private alertSerive: AlertService) { }

  ngOnInit() {
  }

  trigerAlert(){


  	//your code goes here
  	//It may http request
  	//or any other
  	//So you can use this alert service any where in your application

  	this.alertSerive.create(
  		"Title", //title
  		"danger", //type
  		5000, // time
  		"success Alert" //body
  		);
  }

}

When “triggerAlert “method is called (by an event like button click), our custom alert will pop-up according to the configuration that you made.

Notice: You can pass title, type (danger, infor, success), time ( in milliseconds) and body as your requirements.

So, now you are ready to use the custom alerts module in your Angular project.

Find the project on github: click here

If you have any problem, please comment in the comment section. If you like this tutorial don’t forget to share.

Thank you for reading.

Please follow us:
error

Leave a Reply

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

*
*

FACEBOOK
FACEBOOK
YOUTUBE
YOUTUBE