py-trade / src /app /chatbot /chatbot.ts
Oviya
update chatbot ui
becf4e3
import { Component, ElementRef, ViewChild } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { CommonModule } from '@angular/common';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { ChatBotService } from './chatbot.service';
import { MarkdownModule } from 'ngx-markdown';
type ChatPair = { user: string; bot: string | null };
@Component({
selector: 'app-chatbot',
standalone: true,
imports: [CommonModule, HttpClientModule, FormsModule, MarkdownModule],
templateUrl: './chatbot.html',
styleUrls: ['./chatbot.scss'],
})
export class Chatbot {
@ViewChild('chatBox') chatBoxRef!: ElementRef<HTMLDivElement>;
question: string = '';
loading: boolean = false;
messages: ChatPair[] = [];
constructor(private chatService: ChatBotService) { }
askQuestion(): void {
const q = this.question.trim();
if (!q) return;
// push one pair: user + empty bot (will show typing dots)
this.messages.push({ user: q, bot: '' });
this.question = '';
this.loading = true;
this.scrollToBottomSoon();
this.chatService.generateResponse(q).subscribe({
next: (response) => {
const answer = response?.answer ?? 'No response received.';
this.messages[this.messages.length - 1].bot = answer;
this.loading = false;
this.scrollToBottomSoon();
},
error: () => {
this.messages[this.messages.length - 1].bot =
'Error: Could not get a response from the server.';
this.loading = false;
this.scrollToBottomSoon();
},
});
}
isLast(msg: ChatPair): boolean {
return this.messages.length > 0 && this.messages[this.messages.length - 1] === msg;
}
trackByIndex(index: number): number {
return index;
}
private scrollToBottomSoon() {
// Wait for DOM update
setTimeout(() => {
try {
const el = this.chatBoxRef?.nativeElement;
if (el) el.scrollTop = el.scrollHeight;
} catch { }
}, 0);
}
}