如何使用angular 4在完美滚动条中启用自动滚动?

如何使用angular 4在完美滚动条中启用自动滚动?,angular,perfect-scrollbar,Angular,Perfect Scrollbar,这里的文档不是很有用。我想在我的应用程序中使用完美的滚动条,这样我就可以绕过与所有浏览器兼容的问题。我完全按照这里的描述初始化了代码。 这就是我在html中所做的 {{messages}} 现在,对于每个新消息,我希望容器自动滚动到最新消息。进一步阅读文档,我发现有调用事件的指令。这在我前面链接的文档末尾描述。因此,在同一部分中,我的方法如下: import {PerfectScrollbarComponent } from 'ngx-perfect-scrollbar'; ... c

这里的文档不是很有用。我想在我的应用程序中使用完美的滚动条,这样我就可以绕过与所有浏览器兼容的问题。我完全按照这里的描述初始化了代码。 这就是我在html中所做的



{{messages}}
  • 现在,对于每个新消息,我希望容器自动滚动到最新消息。进一步阅读文档,我发现有调用事件的指令。这在我前面链接的文档末尾描述。因此,在同一部分中,我的方法如下:

    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实现自动滚动吗?
    提前谢谢你

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

    HTML:


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

    @ViewChild(PerfectScrollbarComponent)
    scrollbar?: PerfectScrollbarComponent;
    
    假设最新消息出现在列表底部,则可以使用directiveRef上提供的scrollToBottom方法

    this.scrollbar.directiveRef.scrollToBottom(0, 500);  // 500ms is the speed
    

    PS不是我的解决方案中的一个组件, 所有这些解决方案对我都不起作用。我已经把它修好了

    scrollUp(): void {
      const container = document.querySelector('.main-panel');
      container.scrollTop = 0;
    }
    

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

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

    setTimeout()解决了我的问题

    分享下面的代码

    HTML:

    this.scrollbar.directiveRef.scrollToBottom(0, 500);  // 500ms is the speed
    
    scrollUp(): void {
      const container = document.querySelector('.main-panel');
      container.scrollTop = 0;
    }
    
    <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>
    
    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);
       }