文档在这里不是很有帮助。我想在我的应用程序中使用完美的滚动条,以便绕过与所有浏览器兼容的问题。我完全按照此处所述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>
现在,对于每个新消息,我希望容器自动滚动到最新消息。进一步阅读文档,我发现有&#39;是调用事件的指令。我之前链接的文档末尾描述了这一点。所以我的方法在同一个组件中如下:
import {PerfectScrollbarComponent } from 'ngx-perfect-scrollbar';
...
constructor(private scrollbar:PerfectScrollbarComponent) { }
...
ngDoCheck() {
var chat = document.getElementById('chat');
this.scrollbar.directiveRef.scrollToBottom(chat.scrollHeight);
}
这给了我一个错误,因为它期望PerfectScrollbarComponent成为提供者。在我这样做之后,我得到另一个错误没有ElementRef的提供者!。
我正在为此而失眠。任何人都可以建议如何使用angular 4中的perfectscrollbar实现自动滚动? 提前谢谢
答案 0 :(得分:2)
我也花了很多时间在这上面并解决了这个问题如下:
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)
}
}
答案 1 :(得分:2)
顾名思义,PerfectScrollbarComponent是一个组件,因此无需注入它,而需要使用@ViewChild
对其进行引用。@ViewChild(PerfectScrollbarComponent)
scrollbar?: PerfectScrollbarComponent;
假设最新消息出现在列表的底部,则可以使用指令Ref上可用的scrollToBottom方法
this.scrollbar.directiveRef.scrollToBottom(0, 500); // 500ms is the speed
答案 2 :(得分:0)
PS不是我的解决方案的组成部分, 所有这些解决方案都不适合我。我已经像下面一样固定了
scrollUp(): void {
const container = document.querySelector('.main-panel');
container.scrollTop = 0;
}
答案 3 :(得分:0)
花了这么多时间后,我使用 Perfect-scrollbar 指令解决了我的问题。
我的问题是在数据库中添加新消息,然后滚动到新消息。尝试了很多方法,但
<块引用>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);
}