我知道这个问题以前被问过,但没有一个解决方案对我有用。
我正在从事 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。
我的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。但没有任何组件触发该事件。我做错了什么?
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>
在你的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.
}