10

文档在这里不是很有帮助。我想在我的应用程序中使用完美的滚动条,以便绕过与所有浏览器的兼容性问题。我完全按照这里的描述初始化了我的代码https://github.com/zefoy/ngx-perfect-scrollbar/tree/4.xx/。这就是我在我的 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 成为提供者。在我这样做之后,我得到另一个错误 No provider for ElementRef!。

我为此失眠了。任何人都可以提出有关如何在角度 4 中使用完美滚动条实现自动滚动的建议吗?先感谢您

4

4 回答 4

5

我也花了很多时间解决这个问题,如下:

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)
  }
}
于 2018-01-09T15:52:54.123 回答
3

PerfectScrollbarComponent 顾名思义是一个组件,因此您需要使用 @ViewChild 获取对它的引用,而不是注入它

@ViewChild(PerfectScrollbarComponent)
scrollbar?: PerfectScrollbarComponent;

假设最新消息出现在列表的底部,您可以使用directiveRef 上可用的scrollToBottom 方法

this.scrollbar.directiveRef.scrollToBottom(0, 500);  // 500ms is the speed
于 2018-11-02T01:44:32.720 回答
1

在花了这么多时间之后,我使用完美滚动条指令解决了我的问题。

我的问题是在数据库中添加新消息,然后滚动到新消息。尝试了很多方法但是

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);
   }
于 2021-01-08T00:49:32.043 回答
0

PS 不是我的解决方案中的一个组件,所有这些解决方案都不适合我。我已经固定如下

scrollUp(): void {
  const container = document.querySelector('.main-panel');
  container.scrollTop = 0;
}
于 2020-06-09T07:39:24.687 回答