Angular 2 Hover event

前端 未结 9 1153
深忆病人
深忆病人 2020-12-02 06:20

In the new Angular2 framework, does anyone know the proper way to do a hover like an event?

In Angular1 there was ng-Mouseov

9条回答
  •  隐瞒了意图╮
    2020-12-02 06:38

    You can do it with a host:

    import { Directive, ElementRef, Input } from '@angular/core';
    
    @Directive({
      selector: '[myHighlight]',
      host: {
        '(mouseenter)': 'onMouseEnter()',
        '(mouseleave)': 'onMouseLeave()'
      }
    })
    export class HighlightDirective {
      private _defaultColor = 'blue';
      private el: HTMLElement;
    
      constructor(el: ElementRef) { this.el = el.nativeElement; }
    
      @Input('myHighlight') highlightColor: string;
    
      onMouseEnter() { this.highlight(this.highlightColor || this._defaultColor); }
      onMouseLeave() { this.highlight(null); }
    
       private highlight(color:string) {
        this.el.style.backgroundColor = color;
      }
    
    }
    

    Just adapt it to your code (found at: https://angular.io/docs/ts/latest/guide/attribute-directives.html )

提交回复
热议问题