how to enable autoscrolling in perfect-scrollbar with angular 4?

这一生的挚爱 提交于 2020-06-11 00:39:36

问题


documentation is not being very helpful here. I want to use the perfect scroll-bar in my application so that I bypass issues of compatibility with all browsers. I initialized my code exactly as described here https://github.com/zefoy/ngx-perfect-scrollbar/tree/4.x.x/ . This is what I did in my html

<perfect-scrollbar id="chat" [config]="config"> <li *ngFor="let message of messages"> {{messages}} <li> </perfect-scrollbar>

now for each new message I want the container to autoscroll to the latest message. Reading further the documentation I found that there'are directives to call events. that is described at the end of the document I linked earlier. So my approach has been the following in the same component:

import {PerfectScrollbarComponent } from 'ngx-perfect-scrollbar';
...

constructor(private scrollbar:PerfectScrollbarComponent) { }
...

  ngDoCheck() {
    var chat = document.getElementById('chat');
    this.scrollbar.directiveRef.scrollToBottom(chat.scrollHeight);
  }

This gives me an error because it's expecting PerfectScrollbarComponent to be a provider. After I do that, I get another error No provider for ElementRef!.

I am loosing my sleep over this. Can anyone suggest a suggestion on how to implement autoscrolling with perfectscrollbar in angular 4? Thank you in advance


回答1:


I also spent a lot of time on this and solved this problem as follows:

HTML:

<perfect-scrollbar class="window__list">
  ...
</perfect-scrollbar>

Component:

...
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)
  }
}



回答2:


PerfectScrollbarComponent is a component as the name suggests, so instead of injecting it, you need to get a reference to it using @ViewChild

@ViewChild(PerfectScrollbarComponent)
scrollbar?: PerfectScrollbarComponent;

Assuming the latest message appear at the bottom of the list, you can use scrollToBottom method available on the directiveRef

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



回答3:


PS is not a component in my solution, All of these solutions didn't work for me. I've fixed like below

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


来源:https://stackoverflow.com/questions/47307713/how-to-enable-autoscrolling-in-perfect-scrollbar-with-angular-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!