Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 398
Baruch Avatar asked Dec 18 '22 11:12

Baruch


1 Answers

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;
    }
`]
like image 137
yurzui Avatar answered Dec 23 '22 23:12

yurzui