javascriptangularchatchatbotnebular

Nebular chat component - not scrolling to bottom automatically?


I am using Nebular with Angular, specifically the chat UI component. I have mainly used it from default and haven't changed much - however when I test it and add new messages the window doesn't automatically scroll to the bottom. This is obviously quite a bit user experience and I don't know how to change it. Not sure which file to look at as there are so many chat component files but these are my main chatbot files:

chatbot.component.html:

<nb-chat title="Conversation with a Bot">

    <nb-chat-message *ngFor="let msg of messages"
                     type="text"
                     [message]="msg.text"
                     [reply]="msg.reply"
                     [sender]="msg.sender"
                     [date]="msg.date"
                     [avatar]="msg.avatar">
    </nb-chat-message>


    <nb-chat-message *ngIf="loading" [nbSpinner]="loading" nbSpinnerStatus="info"
        type="text"
        avatar="/assets/gcp.png"
        message="...">

    </nb-chat-message>


  <nb-chat-form (send)="handleUserMessage($event)"></nb-chat-form>

</nb-chat>

Part of my chatbot.component.ts

@Component({
  selector: 'app-chatbot',
  templateUrl: './chatbot.component.html',
  styleUrls: ['./chatbot.component.scss']
})

Another part of the chatbot.component.ts

  addBotMessage(text) {
    this.messages.push({
      text: text,
      sender: 'Bot',
      avatar: '/assets/gcp.png',
      date: new Date()
    });
  }

Also as a bonus does anyone know how to get the time with the date, as it's currently only producing the current date without time.


Solution

  • I'm not familiar with the Nebular Component however I see the method addBotMessage which I believe is triggered once the message is coming in. All you need to do is to add window.scroll method to addBotMessage()

    window.scroll(0,document.body.scrollHeight)
    

    Which works for all common browsers. Scroll to top would be:

      window.scroll(0,0)
    

    apply for your method:

      addBotMessage(text) {
        this.messages.push({
          text: text,
          sender: 'Bot',
          avatar: '/assets/gcp.png',
          date: new Date()
        });
        window.scroll(0,document.body.scrollHeight)
      }
    

    Hope it helped.