我已经定义了模板
@Component({
selector: 'name',
directives: [ ... ],
templateUrl: 'name.html'
})
Run Code Online (Sandbox Code Playgroud)
和班级
export class ProductGridComponent implements OnInit {
@HostListener('scroll', ['$event'])
onScroll(e) {
alert(window.pageYOffset)
}
products = [];
}
Run Code Online (Sandbox Code Playgroud)
但它没有拍摄任何东西,但是当我用click和onClick替换scroll和onScroll时它确实显示了警告.
为什么它不能用于滚动,angular2是否有任何其他实现呢?
谢谢
Fla*_*ken 10
假设您要显示主机滚动(而不是Windows窗口)并且您正在使用角度+2.1
@HostListener('scroll', ['$event']) private onScroll($event:Event):void {
console.log($event.srcElement.scrollLeft, $event.srcElement.scrollTop);
};
Run Code Online (Sandbox Code Playgroud)
小智 8
您可以创建像bellow一样的自定义指令
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[scroller]'
})
export class ScrollerDirective {
@HostListener('scroll') scrolling(){
console.log('scrolling');
}
@HostListener('click') clicking(){
console.log('clicking...');
}
constructor() { }
}
Run Code Online (Sandbox Code Playgroud)
然后假设你有一个类似的html模板
<div class="full-width" scroller>
<div class="double-width"></div>
</div>
Run Code Online (Sandbox Code Playgroud)
使用以下css
.full-width{
width: 200px;
height: 200px;
overflow: auto;
}
.double-width{
width:400px;
height: 100%;
}
Run Code Online (Sandbox Code Playgroud)
如果移动水平滚动条,控制台将在运行应用程序时打印"滚动".
关键是 - scoller指令应该在父级而不是子级div中.
小智 7
@HostListener('document:wheel', ['$event.target'])
public onWheel(targetElement) {
console.log()
}
Run Code Online (Sandbox Code Playgroud)
您也可以通过以下代码来完成:
import { HostListener} from "@angular/core";
@HostListener("window:scroll", [])
onWindowScroll() {
//we'll do some stuff here when the window is scrolled
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
29795 次 |
| 最近记录: |