在angular4.X里使用mCustomScrollbar滚动条插件
对其配置,有的时候会出现问题,可以尝试更换一下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 Bubbling:https://segmentfault.com/a/1190000009149495
以下为html使用指令时的代码:
<perfect-scrollbar style="max-height: 366px" (psYReachEnd)="psYReachEnd('getCertification')" *ngIf="Certifications.length>0">
内容
</perfect-scrollbar>
这里的psYReachEnd是在指令里自己定义的一个事件,为啦实现在滚动条滚到底部请求新数据更新数据。
在组件里定义的滚动到底部触发自定义事件后调用的方法:


浙公网安备 33010602011771号