【问题标题】:Angular Dart component scroll eventAngular Dart 组件滚动事件
【发布时间】:2020-10-24 21:29:34
【问题描述】:

我想在用户将页面滚动 500 像素后显示一个“返回顶部”按钮。在 AppComponent 中,我试图在主 Div 中捕获滚动事件。

<div class="container" scrollable>
    <router-outlet [routes]="Routes.all" ></router-outlet>
</div>

Div 和 Directive 中的(滚动)事件似乎都不起作用。

 @Directive(selector: '[scrollable]')
  class ScrollableDiv {
    final Element e;
    ScrollableDiv(this.e);
    void scrollUpdate(){
      window.onScroll.listen((event) { print('Scrolling');});
    }

    @HostListener('scroll')
    void scrolling(){
     scrollUpdate();
    }
  }

但是,如果我将“单击”添加到 @HostListener 而不是“滚动”,那么在单击页面后,我可以捕获滚动事件。如何在不点击的情况下开始收听滚动以及如何从“事件”获取 Y 偏移值?

【问题讨论】:

  • 我不清楚你想做什么。您想触发滚动条位置的变化还是想在用户滚动鼠标滚轮时触发?后者需要 "wheel" 事件。

标签: angular dart


【解决方案1】:

我发现了两种方法。

  1. 将“鼠标悬停”而不是“滚动”添加到@HostListener。我想它会在 99% 的情况下工作,因为用户总是在滚动之前悬停页面。
@Directive(selector: '[scrollable]')
class ScrollableDiv {
  final Element e;
  ScrollableDiv(this.e);
  void scrollUpdate(){
    window.addEventListener('scroll', (event) {
      var last_known_scroll_position=window.scrollY; 
      print(last_known_scroll_position);
    } );      
  }

  @HostListener('mouseover')
  void scrolling(){
    scrollUpdate();
  }
}
  1. 使用 ngOnInint。如果你不添加 ngOnDestroy 可能会导致内存泄漏,但我在主 AppComponent 中使用我的监听器,所以我不需要在页面实际关闭之前将其销毁。
@override
void ngOnInit() {
 window.addEventListener('scroll', (event) {
  var last_known_scroll_position=window.scrollY; 
  print(last_known_scroll_position);
 });  
}

所以我在不破坏监听器的情况下使用了第二个。

【讨论】:

  • 为什么需要鼠标悬停?滚动事件应该足够了
  • 考虑到指令是疯狂的可重用。如果明天您需要在其他地方使用它,则可能需要 ngOnDestroy。无论如何,我建议您添加它。顺便说一句,我更喜欢@HostListener 语法。应该足够了。
  • 如果问题是获取滚动/滚轮事件,请将以下内容添加到“@HostListener”:@HostListener('scroll', ['\$event']) onHostScroll(event) { ... . }
猜你喜欢
  • 2014-11-28
  • 1970-01-01
  • 2020-01-01
  • 2017-09-10
  • 1970-01-01
  • 2017-10-20
  • 2014-12-09
  • 2019-04-10
  • 1970-01-01
相关资源
最近更新 更多