滚动事件未在Angular-6中触发

时间:2018-09-21 09:16:08

标签: html css javascript-events angular6 window-scroll

我知道之前曾问过这个问题,但是没有一个解决方案对我有用。

我正在从事Angular-6项目。我正在尝试在名为 SectionComponent 的组件之一中获取Window-Scroll事件。

html body 标签的样式:

html, body {
    overflow: auto;
    position: relative;
    margin: 0;
    height: 100%;
}

下面是组件层次结构,它说明了如何管理组件。

我的 AppComponent

HTML:

<div id="wrapper">
    <router-outlet></router-outlet>  
</div>

CSS:

#wrapper {
    width: 100vw;
    height: 100vh;
    position: relative;
    overflow: auto;
}

app.component.ts:

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

AppComponent 会在 router-outlet 标签中加载名为 HomeComponent 的组件。此 HomeComponent 通过使用is选择器加载 SectionComponent

我的家庭组件:

HTML:

<div class="home-wrapper">
  <div> 
    <!-- Some content more that window height -->
  </div>
  <app-section></app-section>
</div>

CSS:

.home-wrapper {
    position: relative;
    overflow-y: auto;
    height: 100%;
}

home.component.ts:

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

我的 SectionComponent

HTML:

<div class="section-wrapper">
  <!-- Some content more than window height -->
</div>

CSS:

.section-wrapper {
  position: relative;
  height: 2241px;
}

section.component.ts:

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

我只想在 SectionComponent 中使用Window-Scroll。但是,没有任何一个组件触发该事件。我在做什么错了?

3 个答案:

答案 0 :(得分:0)

我在这里回答我的问题。

我实际上使它正常工作。在对同一问题进行了更多研究之后,我了解到要获取窗口滚动事件,实际的滚动元素应为 document(表示HTML的正文)

我的 HomeComponent 身体的孩子,并且也是可滚动的。这就是为什么它不触发窗口滚动事件。

我为使其生效而进行的更改:

AppComponent CSS

#wrapper {
    width: 100vw;
    height: 100vh;
    position: relative;
}

HomeComponent CSS:

.home-wrapper {
    position: relative;
}

答案 1 :(得分:0)

import { ScrollDispatcher } from '@angular/cdk/scrolling';

  constructor(private scrollDispatcher: ScrollDispatcher) {    
    this.scrollDispatcher.scrolled().subscribe(x => console.log('I am scrolling'));
  }

临时:

<div cdkScrollable>
  <div *ngFor="let one of manyToScrollThru">
    {{one}}
  </div>
</div>

答案 2 :(得分:-1)

在类声明之后的SectionComponent中,只需使用

@HostListener('window:scroll', ['$event']) onScrollEvent($event){

var element =  document.getElementsByClassName('section-wrapper')[0];
var rect =   element.getBoundingClientRect();
 // the above code will return the CSS border-boxe associated with the element.
// so on scroll you will have readonly left, top, right, bottom, x, y, width, and height properties .
//on behalf of these properties you can manipulate the DOM section-wrapper div.

} 
相关问题