Angular4 Notification Component and Service

I have created notification service and component for example some one add,update,delete or edit or anything it will show message related to the functionality.
Demo

notify.service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class NotifyService{
message:string;
private messageSource = new BehaviorSubject<any>('yuiyu');
currentMessage = this.messageSource.asObservable();
  myMethod({message,type}) {
               this.messageSource.next({message,type});
        }
   }

To share data between components if there is any relation we can use input or output when there is no relation between any component then RXJS BehaviorSubject is best option just create a service and inject in any component in application this is what we are going to create now.

notification.component.ts
import { Component, OnInit } from '@angular/core';
import { NotifyService } from '../notify.service';
@Component({
  selector: 'app-notification',
  templateUrl: 'notification.component.html',
  styleUrls: ['./notification.component.css']
})
export class NotificationComponent  {
message:any;
type:any;
 constructor(private _exampleService: NotifyService) { 
    this._exampleService.currentMessage.subscribe((data) => {
                    this.message = data; 
                     console.log(data);
                      setTimeout(() => this.message = '', 1000);
            });
           
           
  }
 }

I have added notify service in notification component so that we can get the data through service will show through notification component in application.

notification.component.html

We will get the notification message according to what we have passed.

<div *ngIf="message.type == 'success'" class="alert alert-success" role="alert">
{{message.message}}
</div>
<div *ngIf="message.type == 'warning'" class="alert alert-warning" role="alert">
{{message.message}}
</div>
<div *ngIf="message.type == 'dark'" class="alert alert-dark" role="alert">
{{message.message}}
</div>


Suppose this is our component we want to show notification message i have added notification component and notify service in app.component.ts

app.component.ts
import { Component, OnInit } from '@angular/core';
import { NotifyService } from './notify.service';
import { NotificationComponent } from './notification/notification.component';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
 _submit:boolean = false; 
 item:string;
 items:Array<string> = ['USA','India'];
   constructor(private _exampleService: NotifyService) {}
  addItem(){
   if(this.item){
      this.items.unshift(this.item)
      this._exampleService.myMethod({message:'Country  added successfully', type:'success'});
    }
    else{
      this._submit = true;
    }
 }
 deleteItem(index){
  for(let i =0; i <= this.items.length; i++){
        if(i == index){
            this.items.splice(i,1)
        }
 }
 this.item= ""
  this._exampleService.myMethod({message:'Country deleted successfully', type:'warning'});
}
editItem(index){
   for(let i =0; i <= this.items.length; i++){
      if(i == index){
            this.item = this.items[i]
        }
   } 
}
 updateItem(index){
   if(this.item){
  for(let i =0; i <= this.items.length; i++){
         if(i == index){
              this.items[i] = this.item;
        }
 }
   this._exampleService.myMethod({message:'Country updated successfully', type:'dark'});
   }
   else{
     this._submit = true;
      }
 }
}
app.component.html

You can see i have added app-notification tag where i can show the notification message

<app-notification></app-notification>
<div class="container"><br>
   <form #f="ngForm" (ngSubmit)="addItem()">
  <div class="row">
   
  <div class="col-md-10"><input type="text" #itemVar=ngModel [(ngModel)]="item" name="item"  class="form-control" placeholder="Add Country" required>
     <div *ngIf="itemVar.invalid && (itemVar.dirty || itemVar.touched) || itemVar.invalid && _submit" class="alert alert-danger">
          <div *ngIf="itemVar.errors.required">
            Country is required
         </div>
        </div>
  </div>
  <div class="col-md-2"><button type="submit" class="btn btn-primary">Add</button></div>

</div></form><br>
 <div class="row">
<div class="col-md-12"><ul class="list-group">
  <li *ngFor= "let item of items; let i = index " class="list-group-item d-flex justify-content-between align-items-center">
    {{item}}
    <div class="btn-group" role="group" aria-label="Basic example">

  Delete
  Edit
  Update
    </div>
  </li>

</ul></div></div>
</div>

This is our root module app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule }   from '@angular/forms';
import { AppComponent } from './app.component';
import { NotifyService } from './notify.service';
import { NotificationComponent } from './notification/notification.component';

@NgModule({
  declarations: [
    AppComponent,
    NotificationComponent
  ],
  imports: [
    BrowserModule,FormsModule
  ],
  providers: [NotifyService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Demo

Leave a Reply

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