在angular4.X里使用mCustomScrollbar滚动条插件

时间:2018-12-11
本文章向大家介绍在angular4.X里使用mCustomScrollbar滚动条插件,主要包括在angular4.X里使用mCustomScrollbar滚动条插件相关应用实例、知识点总结和注意事项,具有一定的参考价值,需要的朋友可以参考一下。

参考网上的方法https://stackoverflow.com/questions/36755625/how-to-import-jquery-and-mcustomscrollbar-plugin-into-angular2-component

对其配置,有的时候会出现问题,可以尝试更换一下mCustomScrollbar的版本。

可以不用install在项目里,直接将所需的js和css下载下来后放在项目的静态文件夹目录下。然后在angular.json里对其引用。

如下图为必须文件:

一些扩展功能需要mousewheel.js。

然后在angular.json里引用:

插件是基于jquery的,所以需要先引用jquery。

这样基本的就处理好了,去将其自定义为指令就可以在项目里随处使用啦。

以下为定义指令文件代码:

import {Directive, ElementRef, OnInit, Output, EventEmitter} from '@angular/core';
// import * as $ from 'jquery';
declare var $: any;
@Directive({
  selector: 'perfect-scrollbar',
  host: {'class': 'mCustomScrollbar'}
})
export class ScrollbarComponent implements OnInit {
    @Output() psYReachEnd = new EventEmitter();
  el: ElementRef;
  constructor(el: ElementRef) {
    this.el = el;
  }
  ngOnInit() {
    const psYReachEnd = this.psYReachEnd;
    // console.log(this.el);
    // console.log($('.mCustomScrollbar'));
    let scrollAxis = 'y';
    if (this.el.nativeElement.getAttribute('data-scroll') === 'X') {
      scrollAxis = 'x';
    }
    $(this.el.nativeElement).mCustomScrollbar({
      autoHideScrollbar: true,
      setHeight: '100%',
      theme: 'light',
      axis: scrollAxis,
      callbacks: {
          whileScrolling: function(){       // 只要滚动条滚动,这个函数就会执行
              if (this.mcs.topPct >= 99) {    // 这表示当滚动条滚动到这个div的90%(当然这个值是可变的)的时候调用下面的代码,
                  psYReachEnd.emit();
              }
          }
          /*onTotalScroll: () => {
              this.psYReachEnd.emit();
          }*/
      }
    });
  }
}

其中使用@Output和EventEmitter自定义事件,然后在滚动条插件的配置里,配置好当滚动到底部时通过emit()去触发这个自定义的事件。插件的callbacks的所有方法可以查看插件官网的说明。http://manos.malihu.gr/jquery-custom-content-scroller/#callbacks-section

https://www.cnblogs.com/LY-leo/p/5750059.html 

自定义事件说明:Angular 4.x Events Bubblinghttps://segmentfault.com/a/1190000009149495

以下为html使用指令时的代码:

<perfect-scrollbar style="max-height: 366px" (psYReachEnd)="psYReachEnd('getCertification')" *ngIf="Certifications.length>0">
  内容 </perfect-scrollbar>

这里的psYReachEnd是在指令里自己定义的一个事件,为啦实现在滚动条滚到底部请求新数据更新数据。

在组件里定义的滚动到底部触发自定义事件后调用的方法: