当前位置: 首页 > 工具软件 > ngx-weui > 使用案例 >

angular2-6 修改ngx-weui 的infiniteloader实现吸顶效果

汝跃
2023-12-01

主要修改compontent组件,为其加入吸顶监听

export class InfiniteloaderComponent implements OnChanges, OnInit, AfterViewInit, OnDestroy {

  private didScroll = false;
  private scrollEvent: any = null;
  private scrollTime: any = null;
  private disposeScroller: Subscription;

  _loading: boolean = false;
  _finished: boolean = false;

  /**
   * 吸顶元素
   */
  toTopElement: any;
  /**
   * 吸顶元素原始距离顶部距离
   */
  toTop: number;

  /**
   * 配置项
   */
  @Input() config: TxInfiniteLoaderConfig;

  /**
   * 吸顶id
   */
  @Input() toTopId;

  /**
   * 加载更多回调
   */
  @Output() loadmore = new EventEmitter<TxInfiniteloaderComponent>();

  constructor(
    private el: ElementRef,
    private zone: NgZone,
    private DEF: TxInfiniteLoaderConfig,
    private renderer2: Renderer2
  ) { }

  /** 设置本次加载完成 */
  resolveLoading() {
    this._loading = false;
    this._finished = false;
  }

  /** 设置结束 */
  setFinished() {
    this._loading = false;
    this._finished = true;
  }

  /** 设置重新开始 */
  restart() {
    this._finished = false;
  }

  _onScroll() {

    if (this._loading || this._finished) {
      return;
    }
    const target = this.scrollEvent.target;
    const scrollPercent = Math.floor(
      (target.scrollTop + target.clientHeight) / target.scrollHeight * 100,
    );

    if (scrollPercent > this.config.percent) {
      this._loading = true;
      this.loadmore.emit(this);
    }

  }

  _fixedListener() {
    /**
    * 元素吸顶
    */
    if (this.toTopElement != null) {
      if (this.scrollEvent.target.scrollTop >= this.toTop) {
        this.renderer2.setStyle(this.toTopElement, 'position', 'fixed');
      } else {
        this.renderer2.setStyle(this.toTopElement, 'position', 'static');
      }
    }
  }

  ngOnInit() {
    this.parseConfig();

    this.scrollTime = setInterval(() => {
      if (this.didScroll) {
        this.didScroll = false;
        this._onScroll();
      }
    }, this.config.throttle);

    this.disposeScroller = fromEvent(
      this.el.nativeElement.querySelector('.weui-infiniteloader__content'),
      'scroll',
    ).subscribe(($event: any) => {
      this.scrollEvent = $event;
      this.didScroll = true;
      this._fixedListener();
    });
  }

  ngOnChanges(changes: SimpleChanges): void {
    if ('config' in changes) {
      this.parseConfig();
    }
  }

  ngAfterViewInit() {
    setTimeout(() => {
      this.toTopElement = this.el.nativeElement.querySelector('#' + this.toTopId);
      if (this.toTopElement === null) {
        return;
      }
      this.toTop = this.toTopElement.offsetTop;
    }, 0);
  }

  ngOnDestroy(): void {
    if (this.scrollTime) {
      clearTimeout(this.scrollTime);
    }
    if (this.disposeScroller) {
      this.disposeScroller.unsubscribe();
    }
  }

  private parseConfig() {
    this.config = Object.assign({}, this.DEF, this.config);
  }

}

普通吸顶指令实现 Angular2-6 实现吸顶效果指令

 类似资料: