0

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

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

htmlbody标签的样式:

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

下面是组件的层次结构,它解释了如何管理组件。

我的应用组件

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');
  }

AppComponentrouter-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');
  }

我的部分组件

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 。但是没有一个组件触发该事件。我究竟做错了什么?

4

2 回答 2

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>
于 2020-10-05T10:38:51.957 回答
-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.

} 
于 2018-09-21T14:23:53.287 回答