How to create alerts in Angular

How to create alerts in Angular

angular tutorials

angular tutorials

In this tutorial, I will show how to create a reusable alerts 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 in 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 in this website.

I outlined steps that we want to follow to create reusable alerts in Angular.

1. Create new Angular application.

2. Create alert module.

3. Create alert interface.

4. Create alert service.

5. Create alert component.

6. Create markup and styles.

Use alert service.

So, let’s start!

Create new Angular application to create alerts in Angular

First of all, we need to create new Angular 5 application. If you want know how to create a fresh Angular application, please read my previous post. Click here .

Notice: If you want to integrate this alert service into your existing project, you don’t need to create new application and you don’t need follow exact folder structure that i’m using here.

Create alert module

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, we can see our new 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.

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

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

export * from './modules';

Then, import alert module into app module (or you can import alert module into appropriate level in your project). After importing, 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 { }

Create alert interface

The next step is creating alert interface . So, type ng g interface shared/modules/alert/interfaces/alert and hit enter.

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

As a result, we can see our new interface inside src/app/shared/modules/interfaces folder. Then, open alert.interface.ts and add this 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
}

The thing is we can specify those parameters as our requirements.

Create alert Service

The third step is creating our alert service. Then, type ng g s shared/modules/alert/services/alert on cmd and git enter.

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

As a result, we can see two files  inside the src/app/shared/modules/alert/services folder. Open the alert.service.ts file and add this 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 wiil make the communication among between components.

Create alert component

The fourth step is creating alert component.

Type, ng g c shared/modules/alert in the console and hit enter.

ng g c shared/modules/alert

As a result, we can see alert.component.ts file inside the src/app/shared/modules/alert folder. Don’t worry about other files.

Notice : This command automatically import our alert component into alert module. So, you not need to do it manually.

Then, open alert.module.ts and import alert service. After doing, 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 { }


Open alert.component.module and create application logic to handle our alert. After doing this, our 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;
  }

}

Create markup and styls

Now time to create markup for alerts in Angular project

Then, open alert.component.ts file and create markup for the alerts. After doing this, alert.component.ts 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()">&times;</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. After doing this, alert.component.scss file as follows.

.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;   
}

Furthermore, add “app-alert” selector into app.component.html. Then, app.component.html is as follows. This is a very important step.

<app-alert></app-alert>

Then, import BrowserAnimationModule into app.module.ts. So, the final 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 into our project. Open index.html file and add 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">

OK, we are almost done. Now let me show you how to use this alert service in our project.  You can use this alert service as your requirements.

Notice: Bellow steps not needed. I will do those steps because I want to show you how to use this alert service.

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

So, we have to follow these steps to use alert service in our test component.

01. import our alert service into test.component.ts.

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

Finally, our 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, our custom alert will pop-up according to configuration.

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

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

Find the project on github: click here

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

Thank you for reading.

Summary
How to create alerts in Angular
Article Name
How to create alerts in Angular
Description
In this tutorial, I will show how to create a reusable alerts in Angular 5. I assume that you are familiar with Angular basics and RXJS library. First of all, we need to create new Angular 5 application. Navigate to project folder and open command prompt. Then, type "ng g m shared/modules/alert"
Author
Publisher Name
Angular + Laravel
Publisher Logo
Please follow and like us: