在窗口滚动时,如何捕获滚动值并更改 Angular 2 中 DOM 中组件之一的位置? 我发现可以使用@HostListener,但它对我不起作用,我正在使用以下代码:
import { Component, OnInit, HostListener } from '@angular/core';
@Component({
selector: 'app-submenu',
templateUrl: './submenu.component.html',
styleUrls: ['./submenu.component.scss'],
inputs : ['menuItems']
})
export class SubmenuComponent implements OnInit {
public menuItems;
constructor() { }
ngOnInit() {
}
@HostListener('document:scroll', ['$event']) onScrollEvent($event){
console.log($event);
console.log("scrolling");
}
}
在 Angular 2 中捕获诸如滚动、调整大小等 dom 事件的最佳方法是什么?
最佳答案
您已经在使用一种好方法:@HoSTListener。为了让它工作,最好写一个添加监听器的指令。
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({ selector: '[scroll]' })
export class TrackScrollDirective {
constructor(private el: ElementRef) {
}
@HostListener('document:scroll', []){
onScroll(): void {
this.el.nativeElement.setAttribute('style','position:fixed')
}
}
确保元素有overflow:scroll
关于javascript - 在窗口滚动时更改 Angular 2 中的组件样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45318828/