滚动事件Ionic 2

10
当用户在Ionic 2上滚动时,让我感到困惑。 我的基本意思是,当用户向下滚动页面时,做某事。任何示例都将是很好的。
更新:
我在构造函数中有这个内容,所以当页面滚动时,我想关闭键盘,因为它被留开并且没有其他关闭方式。
import { Component, ViewChild } from '@angular/core';
import { NavController, NavParams, Content } from 'ionic-angular';
import { Keyboard } from '@ionic-native/keyboard';

export class SearchPage {

  @ViewChild(Content)
  content:Content;

  constructor(public keyboard: Keyboard, public formBuilder: FormBuilder, public navCtrl: NavController, public navParams: NavParams, public apiAuthentication: ApiAuthentication, private http: Http) {

    this.content.ionScroll.subscribe((data)=>{
      this.keyboard.close();
    });
  }
}

但我遇到了这个错误Cannot read property 'ionScroll' of undefined,我是不是把它放错了地方?


我假设你的视图中有一个<ion-content>标签?而且你可能需要在Ionic的视图生命周期中订阅事件,而不是在构造函数中。 - devqon
3个回答

38

您可以订阅内容事件。

内容具有 3个输出事件:

  • ionScroll 在每次滚动事件上触发。
  • ionScrollEnd 当滚动结束时触发。
  • ionScrollStart 当首次开始滚动时触发。

监听事件:

@ViewChild(Content)
content: Content;
// ...
ngAfterViewInit() {
  this.content.ionScrollEnd.subscribe((data)=>{
    //... do things
  });
}

或者通过 DOM 完成:

<ion-content (ionScroll)="onScroll($event)">

适用于Ionic 4

<ion-content [scrollEvents]="true" (ionScroll)="onScroll($event)">

谢谢您!我已经更新了问题并附上了一个错误。 - BA1995
你获取到子组件 Content 了吗? - Stubbies
是的,我已经更新了,以展示.ts文件的主要方面。 - BA1995
修改了我的帖子。 - Stubbies
2
在iOS上不起作用,你有其他想法或解决方案吗? - jorghe94
[scrollEvents]="true" 出现错误。无法绑定到 'ion-content' 的 'scrollEvents',因为它不是已知属性。 - Oleg Reym

1

您可以使用ngOnInit方法来注册滚动事件:

ngOnInit() {
   if (this.content) {
      this.content.ionScroll.subscribe((data)=>
        this.keyboard.close();
      });
    }
  }

0

当在自定义指令中尝试时,可以尝试像这样的东西:

import { Renderer2 } from '@angular/core';
...
constructor(private renderer: Renderer2) {}

ngOnInit() {
    this.renderer.listen(this.myElement, 'scroll', (event) => {
        // Do something with 'event'
        console.log(this.myElement.scrollTop);
    });
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接