Hostlistener等

时间:2017-01-24 11:26:59

标签: angular angular2-directives

有没有在间隔中以角度2收听自定义事件?比如3秒一次?

export class scrollDirectiveComponent {
    pageNo: any = 1;
    @Input() pageNumber: any;
    @Output() emitPageNumber: EventEmitter<any> = new EventEmitter();
    @HostListener('scroll', ['$event'])
    onScroll(event) {
        console.log('scrolled', event.target.scrollTop);
        let tracker = event.target;
        let limit = tracker.scrollHeight - tracker.clientHeight - 5;
        console.log(event.target.scrollTop, limit);
        if (event.target.scrollTop > limit) {
            this.pageNumber++;
            this.emitPageNumber.emit(this.pageNumber);
        }
    }
}

继续收听滚动事件,页码自动递增。如果一个人不能等待,那么滚动条是否可以更改为新位置?

1 个答案:

答案 0 :(得分:2)

一旦我理解了你就可以这样做,在你发出的每个滚动事件上都可以观察到可观察的时间段(3000),这意味着只有一个事件会通过。

export class scrollDirectiveComponent {
  pageNumber: any = 1;
  private scrollEvents = new Subject();
  constructor() {
    scrollEvents
      .throttleTime(3000)
      .subscribe(() => {
        this.emitPageNumber.emit(++this.pageNumber);
      });
  }

  @Input() pageNumber: any;
  @Output() emitPageNumber: EventEmitter<any> = new EventEmitter();
  @HostListener('scroll', ['$event'])
  onScroll(event) {
    console.log('scrolled', event.target.scrollTop);
    let tracker = event.target;
    let limit = tracker.scrollHeight - tracker.clientHeight - 5;
    console.log(event.target.scrollTop, limit);
    if (event.target.scrollTop > limit) {
      this.scrollEvents.next(true);
    }
  }
}

看起来的其他选项会是这样的,但我不确定你需要尝试,因为我从未做过指令

constructor(private _el: ElementRef){
  Observable.fromEvent(_el, 'resize')
    .throttleTime(3000)
    .subscribe(() => {
      this.emitPageNumber.emit(++this.pageNumber);
    });
}