Angular Chatbot

What is chatbot 

Chatbots typically imitate or replace human user behavior. Because they are automated, they operate much faster than human users.

Where we use this 

Every application we have help or support pages has some application-related content. So better we can go for chatbot for the customer related query. If we go to a chatbot, can't wait for any customer-related query for a long time, we can get the answer within no time. 

Simple and easy implementation and faster. No need for any backend or API service. We can handle the frontend only. In case you need any backend services you can able to call API service as well. 

Once I create the application, I have added the codes below. 

app.component.css 

.button { 
    margin-right: 20px 
  } 
  .button-active { 
    background-color: #9b4dca; 
    color: white; 
  } 
  .button-active:hover, 
  .button-active:focus { 
    background-color: #9b4dca; 
    border-color: #9b4dca; 
    color: #fff; 
  } 
  .top-bar { 
    margin: 25px 0; 
  }

app.component.html 

<div class="row"> 
  <div class="column"></div> 
  <div class="column column-50"> 
    <router-outlet></router-outlet> 
  </div> 
  <div class="column"></div> 
</div> 

app.component.ts

import { Component } from '@angular/core'; 
@Component({ 
  selector: 'my-app', 
  templateUrl: './app.component.html', 
  styleUrls: ['./app.component.css'], 
}) 
export class AppComponent { 
} 

app.module.ts 

import { NgModule } from '@angular/core'; 
import { BrowserModule } from '@angular/platform-browser'; 
import { FormsModule } from '@angular/forms'; 
import { AppRoutingModule} from './app-router.module' 
import {AngularBotModule} from './angular-bot/angular-bot.module' 
import { AppComponent } from './app.component'; 
@NgModule({ 
  imports:[  
    BrowserModule,  
    FormsModule,  
    AppRoutingModule,  
    AngularBotModule 
  ], 
  declarations: [ AppComponent ], 
  bootstrap:    [ AppComponent ] 
}) 
export class AppModule { } 

I have to add the chat service(chat.service.ts), chat(chat.component.ts, CSS and HTML) & chat modules(angular-bot.module.ts) and chat.

Just copy and paste the code below changes.

chat.service.ts 

import { Injectable } from '@angular/core'; 
import { Observable, Subject } from 'rxjs'; 
export class Message { 
  constructor(public author: string, public content: string) {} 
} 
@Injectable() 
export class ChatService { 
  constructor() {} 
  conversation = new Subject<Message[]>();  
  messageMap = { 
    "Hi": "Hello", 
    "Who are you": "My name is Test Sat Bot", 
    "What is your role": "Just guide for the user", 
    "defaultmsg": "I can't understand your text. Can you please repeat" 
  } 
  getBotAnswer(msg: string) { 
    const userMessage = new Message('user', msg);   
    this.conversation.next([userMessage]); 
    const botMessage = new Message('bot', this.getBotMessage(msg)); 
    setTimeout(()=>{ 
      this.conversation.next([botMessage]); 
    }, 1500); 
  } 
  getBotMessage(question: string){
    let answer = this.messageMap[question]; 
    return answer || this.messageMap['defaultmsg']; 
  } 
}

angular-bot.module.ts 

angular-bot.module.ts 
import { NgModule } from '@angular/core'; 
import { FormsModule } from '@angular/forms'; 
import { CommonModule } from '@angular/common'; 
import { ChatComponent } from './chat/chat.component'; 
import { ChatService } from './chat.service'; 
@NgModule({ 
  imports: [CommonModule, FormsModule], 
  declarations: [ChatComponent], 
  providers: [ChatService], 
}) 
export class AngularBotModule {} 

chat.component.css 

.message { 
    border-radius: 50px; 
    margin: 0 15px 20px; 
    padding: 10px 20px; 
    position: relative; 
    font-size: 20px; 
  } 
  .message.to { 
    background-color: #2095FE; 
    color: #fff; 
    margin-left: 100px; 
    text-align: right; 
  } 
  .message.from { 
    background-color: #E5E4E9; 
    color: #363636; 
    margin-right: 100px; 
  } 
  .message.to + .message.to, 
  .message.from + .message.from { 
    margin-top: -10px; 
} 

chat.component.html 

<ng-container *ngFor="let message of messages"> 
  <div class="message" [ngClass]="{from: message.author === 'bot',to: message.author === 'user'}"> 
    {{ message.content }} 
  </div> 
</ng-container> 
<label *ngIf="messages.length == 0; else dialogInfo" for="nameField">Chat Bot</label> 
<input [(ngModel)]="value" (keyup.enter)="sendMessage()" type="text" /> 
<button (click)="sendMessage()">Send</button> 
<ng-template #dialogInfo> 
  <span [className]="'float-right'">Total messages: {{ messages.length }}</span> 
</ng-template> 

chat.component.ts

import { Component, OnInit } from '@angular/core'; 
import {Message,ChatService} from '../chat.service' 
@Component({ 
  selector: 'app-chat', 
  templateUrl: './chat.component.html', 
  styleUrls: ['./chat.component.css'] 
}) 
export class ChatComponent implements OnInit { 
  messages: Message[] = []; 
  value: string; 
  constructor(public chatService: ChatService) { } 
  ngOnInit() { 
      this.chatService.conversation.subscribe((val) => { 
      this.messages = this.messages.concat(val); 
    }); 
  }
  sendMessage() { 
    this.chatService.getBotAnswer(this.value); 
    this.value = ''; 
  } 
} 

Added all above codes, run the applications using ng serve –open OR npm start command and the application window will open like the below image. 

Next going to enter the text “Hi”, we already mapped text “Hi” for replying with “Hello”. Once you enter “Hi” the service will check the related words and will get the acknowledgment. We set the replied time duration here to 2 seconds in the interval time. 

Next going to enter messages like “Who are you” and the replied message we mapped “My name is Test Sat Bot” message will show and the Total messages count increased parallelly. 

Angular Chatbot

If we enter invalid text or unmapped text we will show default messages like “I can't understand your text. Can you please repeat”. 

Angular Chatbot

In this case, we map the text string of the application or else load the data in a JSON file and refer to the applications. Another way to get the JSON file from the backend is to call the API service and get the JSON file data to import in case we need it dynamically. something any values changes or text changes so directly change from backend and update the application simply. Avoid angular deployment or frontend changes at times and reduce workload. 

I hope this article is most helpful for you. 


Similar Articles