gpt4 book ai didi

angular - 发送消息或在angular2中打开消息后,如何使页面自动向下滚动到底部

转载 作者:行者123 更新时间:2023-12-02 08:07:40 25 4
gpt4 key购买 nike

我有一个消息对话部分,在其中我需要将滚动条显示在底部,并且当页面再次打开时,滚动条必须在底部。我的意思是最后一条消息应该首先显示。

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 => {});
}

最佳答案

这是一个有角度的解决方案:

  • 我添加了#scrollCottom模板变量。
  • 您可以使用ViewChild获取Element引用,并应检查滚动底部问题。

  • 组件;
    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>

    关于angular - 发送消息或在angular2中打开消息后,如何使页面自动向下滚动到底部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50094315/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com