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

问题描述 投票:0回答:2

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

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

htmlbody标签的样式:

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

AppComponentrouter-outlet 标签中加载名为 HomeComponent 的组件。这个 HomeComponent 使用 is 选择器加载 SectionComponent

我的Home组件:

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。但没有任何组件触发该事件。我做错了什么?

html css angular6 dom-events window-scroll
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>

-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.

} 
© www.soinside.com 2019 - 2024. All rights reserved.