【问题标题】:How to detect scroll using Ionic 2+ and Angular 2+?如何使用 Ionic 2+ 和 Angular 2+ 检测滚动?
【发布时间】:2020-02-25 09:09:12
【问题描述】:

是否可以检测到窗口何时滚动?

我已经尝试添加HostListener:

@HostListener("window:scroll", [])
onScroll() {
   console.log('scroll');
}

我已经尝试使用Renderer2:

this.renderer.listen(
   'window',
   'scroll',
   (evt) => {
      console.log('scroll');
   }
);

都不行。

【问题讨论】:

  • 我编辑代码请检查
  • @KiranMistry 它仍然没有工作。不过还是谢谢。
  • 我再次编辑帖子,请查看 ionic

标签: angular ionic-framework ionic2 angular7


【解决方案1】:

Ionic2/3 中的语法不同。应该是这样的:

<ion-content (ionScroll)="scrolling($event)" (ionScrollEnd)="scrollComplete($event)">
  <ion-list>
   ...
  </ion-list>   
</ion-content> 

然后在你的 ts 文件中

constructor(){}
  scrolling(event) {
    // your content here for scrolling
  }

  scrollComplete(event) {
    // your content here of scroll is finished
  }
}

【讨论】:

  • 这是我正在使用的解决方法,但问题是我正在开发一个无法直接访问 ion-content 的 npm 库。最好,我可以从组件内检测滚动,而不必传递 Input()
  • 还需要将 [scrollEvents]="true" 添加到 ion-content 元素中
【解决方案2】:

您可以使用以下代码检测滚动,就像您的第一个代码 sn-p..

 @HostListener('window:scroll')
 onWindowScroll():void {
   let isScrolled = window.scrollY > this.heightToCompare;
   if (isScrolled !== false) {
      //  do what you want  
   } 
 }

【讨论】:

  • 我在我的问题中提到这不起作用。我添加了一个断点和控制台日志,这不会触发。也许是因为离子。
  • @jrquick 它不起作用,因为,您不应该设置 overflow-x: hidden 体内或不应该设置 height:100% 。离子出于某种原因是自动设置高度:100%
【解决方案3】:

在你的 html 文件中添加这个

<ion-content [scrollEvents]="true"></ion-content>

在你的 .ts 文件中添加这个

@HostListener('ionScroll', ['$event']) onScroll(event){
    console.log(event.detail.scrollTop)
    console.log('im scrolling')
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-31
    • 2016-11-05
    • 1970-01-01
    • 2018-04-10
    • 2016-06-26
    相关资源
    最近更新 更多