Here I have created the directive, which emit events on mouse wheel scroll upward and downward
You can use these directives for image zoom-in and zoom-out. Element binds to event DOMMouseScroll ( for firefox ), mousewheel ( for chrome),  onmousewheel (for IE)
Source Code      DEMO

Directive for Mouse Wheel Scroll Up

HTML Usage

<div mouseWheel (mouseWheelUp)="mouseWheelUpFunc(event)" (mouseWheelDown)="mouseWheelDownFunc(event)"></div>

mousewheel.directive.ts

This is attribute directive which catches the mouse wheel scroll event on all type of browsers
import { Directive, Output, HostListener, EventEmitter } from '@angular/core';

@Directive({ selector: '[mouseWheel]' })
export class MouseWheelDirective {
  @Output() mouseWheelUp = new EventEmitter();
  @Output() mouseWheelDown = new EventEmitter();

  @HostListener('mousewheel', ['$event']) onMouseWheelChrome(event: any) {
    this.mouseWheelFunc(event);
  }

  @HostListener('DOMMouseScroll', ['$event']) onMouseWheelFirefox(event: any) {
    this.mouseWheelFunc(event);
  }

  @HostListener('onmousewheel', ['$event']) onMouseWheelIE(event: any) {
    this.mouseWheelFunc(event);
  }

  mouseWheelFunc(event: any) {
    var event = window.event || event; // old IE support
    var delta = Math.max(-1, Math.min(1, (event.wheelDelta || -event.detail)));
    if(delta > 0) {
        this.mouseWheelUp.emit(event);
    } else if(delta < 0) {
        this.mouseWheelDown.emit(event);
    }
    // for IE
    event.returnValue = false;
    // for Chrome and Firefox
    if(event.preventDefault) {
        event.preventDefault();
    }
  }
}

app.module.ts

We should import above directive and include in this module. 
import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { MouseWheelDirective } from './mousewheel.directive';

@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ AppComponent, MouseWheelDirective ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

6 comments:

  1. it's really perfect but can you give me little tip ,how can I disable this directive.

    ReplyDelete
  2. This solution works with angular 4 too. scroll event no longer works with Ng4

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. Thanks man, worked like a charm in angular 4.

    ReplyDelete
  5. Can someone tell me better URL to study angular basic ànd advànced.

    ReplyDelete

Blogroll

Follow this blog by Email

Popular Posts