简体   繁体   中英

How to make HostListener for scroll work?

I'm trying to add a window:scroll listener but when scrolling nothing happens

What I've tried so far:

using host inside component decorator

@Component({
  ...
  host: {
    'window:scroll' : 'onWindowScroll($event)'
  },
  ...
)
export class PageWrapperComponent implements OnInit {
  ...
  public onWindowScroll(event: Event): void {
    console.log('scrolled');
  }
  ...
}

using HostListener inside component decorator

export class PageWrapperComponent implements OnInit {
  ...
  @HostListener('window:scroll', ['$event'])
  public onWindowScroll(event: Event): void {
    console.log('scrolled');
  }
  ...
}

I also tried using it in an attribute directive but it didn't work either

Neither will trigger the console log . I've searched for similar questions in SO but even though my code is essentially the same it still doesn't work.

Using host inside component decorator

it should be:

'(window:scroll)' : 'onWindowScroll($event)'

Plunker Example

Using HostListener inside component decorator Your syntax looks correct

@HostListener('window:scroll', ['$event'])
public onWindowScroll(event: Event): void {
  console.log('scrolled');
}

Plunker Example

You can also make sure that your component has scroll. In my examples i imitate scroll via:

styles: [`
    :host {
      display: block;
      height: 2000px;
    }
`]

My team and I recently ran into this issue. Our solution was to use angular's Renderer to set a listener for the 'scroll' event on the elementRefs parentNode.

`constructor(
  private _renderer: Renderer,
  private _elementRef: ElementRef
) {
  this._renderer.listen(this._elementRef.nativeElement.parentNode, 
   'scroll', (event) => {
      // do stuff with the event
  });
}`

(Posted on behalf of the question author) .

I was able to out why HostListener wasn't working, I am using angular/material component library and I overrode the md-sidenav-layout height with 100vh and it didn't like that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM