scroll event on Hostlistener

后端 未结 5 1360
一生所求
一生所求 2020-12-31 22:19

I have defined template

@Component({
    selector: \'name\',
    directives: [ ... ],
    templateUrl: \'name.html\'
})

and class



        
相关标签:
5条回答
  • 2020-12-31 22:42
    @HostListener('document:wheel', ['$event.target'])
    public onWheel(targetElement) {
        console.log()
    }
    
    0 讨论(0)
  • 2020-12-31 22:50

    Assuming you want to display the host scroll (and not the windows one) and that you are using angular +2.1

      @HostListener('scroll', ['$event']) private onScroll($event:Event):void {
        console.log($event.srcElement.scrollLeft, $event.srcElement.scrollTop);
      };
    
    0 讨论(0)
  • 2020-12-31 22:50

    You can create a custom directive like 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() { }
    
    }
    

    And then assuming you have a html template like

    <div class="full-width" scroller>
        <div class="double-width"></div>
    </div>
    

    use the following css

    .full-width{
        width: 200px;
        height: 200px;
        overflow: auto;
    }
    
    .double-width{
        width:400px;
        height: 100%;
    }
    

    the console will print "scrolling" on running the app if you move the horizontal scroll bar.

    Here the key is that - the scoller directive should be in the parent not in the child div.

    0 讨论(0)
  • 2020-12-31 22:51

    You could do it by the following code as well:

    import { HostListener} from "@angular/core";
    
    @HostListener("window:scroll", [])
    onWindowScroll() {
     //we'll do some stuff here when the window is scrolled
    }
    
    0 讨论(0)
  • 2020-12-31 22:58

    Set (scroll)="yourFunction($event)" within the template at the corresponding element.

    0 讨论(0)
提交回复
热议问题