如何在Angular中使用better-scroll插件

版权声明:著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 https://blog.csdn.net/qq_43168841/article/details/84591034

本文主要介绍了Angular中使用better-scroll插件的方法,小编觉得挺不错的,现在分享给大家。

better-scroll的使用
由于需要在一个固定的的高度做无限滚动,本来css的overflow-y也可以完成的,奈何安卓不是很流畅,还很生硬,就是用了第三方库better-scroll,配合angular的ng-content。angular的ng-content和vue的插槽很像,里面一些不确定的内容可以通过ng-content投影进去。
安装better-scroll

  • 1: npm install better-scroll --save
  • 2: 安装types npm install better-scroll @types/better-scroll --save
  • 3:在angular-cli里面引入

listscroll组件的编写
根据官方的文档可以看出,better-scroll对dom的结构是有要求的,最外层的wrapper那一层是需要固定高度的,里面那一层content是根据内容的高度来撑起的。
html部分:

<div class="scroll" #scroll>
 <ng-content></ng-content>
</div>

ng-content就是要投影进来的内容
component.ts部分
1: import引入 BScroll
2:在OnInit这个钩子里面来初始化,由于OnInit的时候,ngFor还没执行完毕,所以就加了一个定时器来延迟。

import { Component, OnInit, Input, ElementRef, ViewChild } from '@angular/core';
declare let BScroll;
@Component({//欢迎加入全栈开发交流圈一起学习交流:864305860
 selector: 'app-listscroll',
 templateUrl: './listscroll.component.html',
 styleUrls: ['./listscroll.component.css']
})
export class ListscrollComponent implements OnInit { 
 @ViewChild('scroll') scrollEl: ElementRef;
 @Input()
 private height: number; 
 public scroll;
 constructor() { } 
 ngOnInit() {  
  // 设置高度
  this.scrollEl.nativeElement.style.height = `${this.height}px`;    
  // 初始化
  setTimeout(() => {
   this.scroll = new BScroll(this.scrollEl.nativeElement, {click: true});
  }, 20);//欢迎加入全栈开发交流圈一起学习交流:864305860
 } //面向1-3年前端人员
}//帮助突破技术瓶颈,提升思维能力

在其他组件里面使用listscroll组件

<app-listscroll [height]="height">
 <ul>
   <li class="item" *ngFor="let item of list; let num = index;">第{{num}}个</li>
 </ul>
</app-listscroll>

这样better-scroll简单的使用就完成,当然better-scroll还有很多功能,可以依赖它做上拉和下拉的加载,做轮播图等等,具体可参考官方的文档。

结语

感谢您的观看,如有不足之处,欢迎批评指正。

本次给大家推荐一个免费的学习群,里面概括移动应用网站开发,css,html,webpack,vue node angular以及面试资源等。
对web开发技术感兴趣的同学,欢迎加入Q群:864305860,不管你是小白还是大牛我都欢迎,还有大牛整理的一套高效率学习路线和教程与您免费分享,同时每天更新视频资料。
最后,祝大家早日学有所成,拿到满意offer,快速升职加薪,走上人生巅峰。

猜你喜欢

转载自blog.csdn.net/qq_43168841/article/details/84591034