44 lines
1.3 KiB
TypeScript
44 lines
1.3 KiB
TypeScript
import { Component, AfterViewChecked, ViewChild, ElementRef } from '@angular/core';
|
|
import { CommonModule } from '@angular/common';
|
|
import { FormsModule } from '@angular/forms';
|
|
import { ChatService } from './chat.service';
|
|
|
|
@Component({
|
|
selector: 'app-root',
|
|
standalone: true,
|
|
imports: [CommonModule, FormsModule],
|
|
templateUrl: './app.component.html'
|
|
})
|
|
|
|
export class AppComponent {
|
|
userMessage = '';
|
|
resposta: string | null = null;
|
|
chatHistory: { text: string, sender: 'user' | 'bot' }[] = [];
|
|
constructor(private chatService: ChatService) {}
|
|
@ViewChild('chatHistoryDiv') chatHistoryDiv!: ElementRef;
|
|
|
|
ngAfterViewChecked() {
|
|
this.scrollToBottom();
|
|
}
|
|
|
|
scrollToBottom() {
|
|
try {
|
|
this.chatHistoryDiv.nativeElement.scrollTop = this.chatHistoryDiv.nativeElement.scrollHeight;
|
|
} catch (err) {}
|
|
}
|
|
|
|
enviarMensagem() {
|
|
if (!this.userMessage.trim()) return;
|
|
const mensagem = this.userMessage;
|
|
this.chatHistory.push({ sender: 'user', text: mensagem });
|
|
this.userMessage = '';
|
|
this.chatService.sendMessage(mensagem).subscribe({
|
|
next: (res: any) => {
|
|
this.chatHistory.push({ sender: 'bot', text: res.reply || 'Sem resposta do bot.' });
|
|
},
|
|
error: () => {
|
|
this.chatHistory.push({ sender: 'bot', text: 'Erro ao contactar o servidor.' });
|
|
}
|
|
});
|
|
}}
|