文档在这里不是很有帮助。我想在我的应用程序中使用完美的滚动条,以便绕过与所有浏览器的兼容性问题。我完全按照此处 https://github.com/zefoy/ngx-perfect-scrollbar/tree/4.x.x/中所述初始化了我的代码。这就是我在 html 中所做的
<perfect-scrollbar id="chat" [config]="config">
<li *ngFor="let message of messages">
{{messages}}
<li>
</perfect-scrollbar>
现在,对于每条新消息,我希望容器自动滚动到最新消息。进一步阅读文档,我发现有调用事件的指令。这在我之前链接的文档末尾进行了描述。所以我的方法在同一组件中如下:
import {PerfectScrollbarComponent } from 'ngx-perfect-scrollbar';
...
constructor(private scrollbar:PerfectScrollbarComponent) { }
...
ngDoCheck() {
var chat = document.getElementById('chat');
this.scrollbar.directiveRef.scrollToBottom(chat.scrollHeight);
}
这给了我一个错误,因为它期望PerfectScrollbarComponent是一个提供者。这样做后,我收到另一个错误 没有 ElementRef 的提供程序!
我为此失眠了。任何人都可以提出有关如何在角度 4 中使用完美滚动条实现自动滚动的建议吗?提前谢谢你
我也花了很多时间在这个上面,并解决了这个问题,如下所示:
.HTML:
<perfect-scrollbar class="window__list">
...
</perfect-scrollbar>
元件:
...
import { PerfectScrollbarComponent } from 'ngx-perfect-scrollbar';
export class ChatWindowComponent implements OnInit {
...
// Linking to component that using perfect-scrollbar
@ViewChild(PerfectScrollbarComponent) public directiveScroll: PerfectScrollbarComponent;
...
constructor() { }
...
toBottom(): void {
if (isUndefined(this.directiveScroll)) return;
this.directiveScroll.directiveRef.scrollToBottom(0, 100)
}
}
PerfectScrollbarComponent顾名思义是一个组件,所以你需要使用@ViewChild来获取对它的引用,
而不是注入它@ViewChild(PerfectScrollbarComponent)
scrollbar?: PerfectScrollbarComponent;
假设最新消息出现在列表底部,则可以使用指令Ref上可用的scrollToBottom方法。
this.scrollbar.directiveRef.scrollToBottom(0, 500); // 500ms is the speed
花了这么多时间,我使用完美滚动条指令解决了我的问题。
我的问题是在数据库中添加新消息,然后滚动到新消息。尝试了很多方法,但是
setTimeout(( 解决了我的问题
分享下面的代码
.HTML:
<perfect-scrollbar>
<div class="msg-body" [perfectScrollbar] #psBottom="ngxPerfectScrollbar">
<ng-container *ngFor="let msg of messages">
<div class="nk-reply-item">
{{msg.content}}
</div>
</ng-container>
</div>
</perfect-scrollbar>
TS:
import { Component, OnInit, ViewChild } from '@angular/core';
import { PerfectScrollbarDirective } from 'ngx-perfect-scrollbar';
export class MessageComponent implements OnInit {
@ViewChild('psBottom') psBottom: PerfectScrollbarDirective;
messages = []
constructor() {}
addMessage(newMsg) {
// request to backend or simply push the new msg to messages array
setTimeout(() => {
this.psBottom.scrollToBottom(0, 500);
}, 100);
}
<</div>
div class="one_answers"> PS不是我的解决方案中的组件,所有这些解决方案都对我不起作用。我已经像下面这样修复了
scrollUp(): void {
const container = document.querySelector('.main-panel');
container.scrollTop = 0;
}