How to automatically scroll down to the bottom of a div in AngularJS

Discussão em 'Angular' iniciado por tg marcus, Dezembro 24, 2024.

  1. tg marcus

    tg marcus Guest

    I have a chat application in AngularJS im just trying to scroll down all the way to the bottom like most chat apps do. i tried the native element.scrolltop attribute but no success

    code search.component.ts

    import { Component, OnInit,ViewChild, ElementRef } from '@angular/core';
    import { CommonModule } from '@angular/common';
    ...


    @Component({
    ...
    })
    export class SearchComponent{
    ..
    selectedMessages: any[] = []
    ...
    @ViewChild('inboxChat',{static:true}) inboxChat?: ElementRef<HTMLDivElement>;

    constructor(private socketService: SearchService,private router: Router) {
    ...
    }
    ngOnInit() {

    if (this.inboxChat?.nativeElement){
    this.inboxChat.nativeElement.scrollTop = this.inboxChat.nativeElement.scrollHeight
    }
    }

    ngAfterViewInit() {
    // Accessing the DOM element directly
    console.log(this.inboxChat?.nativeElement);

    // Modifying the DOM element
    if(this.inboxChat?.nativeElement)
    this.inboxChat.nativeElement.scrollTop = this.inboxChat?.nativeElement.scrollHeight;

    }

    }



    search.component.html

    <div class="mesgs" *ngIf="selectedMessages !== []" >
    <div #inboxChat class="msg_history">
    ...

    </div>
    </div>


    search.component.css

    ...
    .msg_history {
    height: 516px;
    overflow-y: auto;
    }


    class .msgs doesn't have overflow-y at all and i tried with that class selected as well

    Continue reading...

Compartilhe esta Página