Automating the scrolling function in Angular 2 to automatically navigate to the bottom of the page whenever a message is sent or opened

In my message conversation section, I want to ensure that the scroll is always at the bottom. When the page is reopened, the last message should be displayed first.

HTML:

<ul>
        <li *ngFor="let reply of message_show.messages">
          <img [src]="reply.from_user_image || '../assets/images/msg.png'"/>
          <p><b>{{reply.name}} </b> <span> {{reply.updated_at | date:'dd.MM.yyyy'}} - {{reply.updated_at | date:'h:mm'}}</span></p>
          <p>{{reply.text}}</p>
        </li>
      </ul>

Ts:

loadMessages() {
    this.service
          .getMessages()
          .subscribe(
            data => {
              this.messagesdata = data;
              this.activeMessages = data.filter(msg => msg.active == true && msg.from_user_name !== 'Anonymus' && msg.messages.length > 0)
              this.closedMessages = data.filter(msg => msg.active == false && msg.from_user_name !== 'Anonymus' && msg.messages.length > 0);
              if (this.activeMessages.length > 0) {
                if(!this.message_show) {
                  var test = this.message_show = this.activeMessages[0];
                  this.message = true;
                  this.message_id = this.activeMessages[0].id;
                  this.message_show.messages.map(function(msg) {
                    if(msg.from_user_id == test.from_user_id) {
                      msg.from_user_image = test.from_user_image;
                    } else {
                      msg.from_user_image = test.to_user_image;
                    }
                    if(msg.to_user_id == test.to_user_id) {
                      msg.to_user_image = test.to_user_image;
                    } else {
                      msg.to_user_image = test.to_user_image;
                    }
                  })
                }
              }             
            },error => {});
  }

Answer №1

Here is a solution in angular way:

  • I utilized the #scrollCottom template variable.
  • By using the ViewChild method, you can retrieve the Element reference and address the scroll bottom issue.

Component:

import { AfterViewChecked, ElementRef, ViewChild, OnInit} from 'angular2/core'
@Component({
    ...
})
export class YourComponent implements OnInit, AfterViewChecked {
    @ViewChild('scrollBottom') private scrollBottom: ElementRef;

    ngOnInit() {
        this.scrollToBottom();
    }

    ngAfterViewChecked() {        
     this.scrollToBottom();        
    } 

    scrollToBottom(): void {
        try {
            this.scrollBottom.nativeElement.scrollTop = this.scrollBottom.nativeElement.scrollHeight;
        } catch(err) { }
    }
}

HTML:

<ul #scrollBottom>
  <li *ngFor="let reply of message_show.messages">
    <img [src]="reply.from_user_image || '../assets/images/msg.png'"/>
    <p><b>{{reply.name}} </b> <span> {{reply.updated_at | date:'dd.MM.yyyy'}} - {{reply.updated_at | date:'h:mm'}}</span></p>
    <p>{{reply.text}}</p>
  </li>
</ul>

Answer №2

If you want to automatically scroll to the bottom of a page, you can achieve this by using the following JavaScript code:

 window.scrollTo(0,document.body.scrollHeight);

To learn more about this topic, please visit the discussion thread linked below:

Scroll Automatically to the Bottom of the Page

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Complicated nestjs application successfully resolves path issue

Currently, I am in the process of creating a boilerplate for NestJS and microservices (still a work in progress). The problem arises when trying to run the app or perform tests, resulting in this https://i.sstatic.net/uj4un.png You can find the code on t ...

Error: Can't find module ng-uikit-pro-standard

I am currently working on implementing datatables in Angular with material design. To achieve this, I am referencing a tutorial from this source. The tutorial instructs to import the MdbTableDirective, MdbTablePaginationComponent, and MdbTableService from ...

index signature in TypeScript is an optional feature

Is it possible to create a type with optional namespaces in TypeScript? export interface NodesState { attr1: number; attr2: number; attr3: number; } The goal is to allow users to namespace the type like this: { namespace1: { attr1: 100, ...

Tips for managing transitions when the indicator is clicked by the user

I'm looking for a way to implement logic that determines whether or not a user can change the step by clicking on the indicator (the step number). I need a callback function that triggers every time there is a step change, but also allows me to preven ...

Observe the task while returning - Firebase Functions

I am working on a Firebase Cloud Functions project where I need to run a scraping task within one of the functions. While the scraping is in progress, I also need to provide progress updates to the consumer. For example, informing them when the task is at ...

Retrieve the total number of hours within a designated time frame that falls within a different time frame

Having a difficult time with this, let me present you with a scenario: A waiter at a restaurant earns $15/hour, but between 9:00 PM and 2:30 AM, he gets paid an additional $3/hour. I have the 'start' and 'end' of the shift as Date obje ...

Angular ngFor Directive Failing to Display Menu Item Information on Right-Click Context Menu

Currently encountering an issue with implementing a right-click function in my context menu. The menu items are not appearing due to the second ngFor="let row" condition... however, I require the selected row object from a right click to pass in a JSON val ...

Unable to locate the main source for loading

I am facing an issue with my app where I am unable to load a basic component. It seems like a simple problem, but I just can't seem to figure it out. Here is the code for my component: import { Component, OnInit } from '@angular/core'; imp ...

Creating distinct "ViewContainerRef" containers for separate tabs in mat-tab within Angular

I have created a runtime component module that generates dynamic components by binding HTML data and functions fetched from an API call. These components are then loaded into a container within tabs, which are also dynamically created based on the data. Th ...

Is there a way to trigger the click event in the week view of an Angular 2+ calendar?

https://i.sstatic.net/Vx2x8.png HTML Templates <mwl-calendar-week-view [viewDate]="viewDate" [refresh]="refresh" (click)="weekDayClick($event)"> </mwl-calendar-week-view> In the component file weekDayCl ...

Unable to fulfill the pledge

I'm struggling to receive the promise from the backend after making a get request. Can anyone help me figure out what I might be doing wrong? makeLoginCall(_username: string, _password: string) { let promise = new Promise((resolve, reject) => ...

How can the life cycle of a component be maintained after the constructor until the function in the constructor has finished executing?

I'm currently developing an Angular 2 application. Within this application, I have a component responsible for displaying the menu. This component contains an array of menu items that are initially set to be displayed based on permissions retrieved f ...

What could be causing an error with NextJS's getStaticPaths when running next build?

When attempting to use Next.js's SSG with getStaticPaths and getStaticProps, everything worked fine in development. However, upon running the build command, an error was thrown: A required parameter (id) was not provided as a string in getStaticPath ...

Customizing the default font color in Angular Material

I am currently navigating through theming in Angular Material and feeling a bit disoriented. I have implemented the prebuilt indigo-pink theme by importing it into my styles.scss as shown below: @import "~@angular/material/prebuilt-themes/indigo-pink.css" ...

When testing, the @Input() variable that is inherited and initialized in the child constructor will be null during ngOnInit

I am currently working on testing Angular components using jest. I encountered an issue where a component initializes a variable in its constructor that becomes null during ngOnInit when the component is tested, but remains as expected when the application ...

Troubleshooting compatibility issues between Sailsjs Services and TypeScript in Vscode

Having an issue with TypeScript in a Sails.js application. I am utilizing TypeScript to write my controller and attempting to use Sails.js services within the controllers. However, I encounter a syntax error in VSCODE. Below is the code snippet from MyCo ...

Encountered an HttpErrorResponse while trying to access the API endpoint

I am encountering an issue when trying to update and insert data with a single post request. https://i.sstatic.net/T9UKR.png Below is my API code: https://i.sstatic.net/kkwqs.png Here is the service code: https://i.sstatic.net/IUMSd.png This section ...

Using Angular 4 to retrieve a dynamic array from Firebase

I have a dilemma while creating reviews for the products in my shop. I am facing an issue with the button and click event that is supposed to save the review on the database. Later, when I try to read those reviews and calculate the rating for the product, ...

Trouble arises with connect-mongo, passport, and passport-local-mongoose as session fails to persist

Seeking assistance with saving session and incorporating functionality like req.isAuthenticated(), req.user, etc., but unable to make it work. Session does not persist and seems to be malfunctioning for unknown reasons. app.ts https://pastebin.com/yGvUZh ...

Implementing centralized authentication through an IdentityServer application with the utilization of the resource owner password flow

I am currently developing two Angular 2 applications that will have a .NET Core 1.1 REST backend and be hosted on Azure App Service. My goal is to enable them to share authentication information in order to provide a seamless Single Sign-On experience. Add ...