Angular 2 Hover事件


196

在新的Angular2框架中,是否有人知道像事件一样进行悬停的正确方法?

Angular1中ng-Mouseover,但似乎没有保留

我已经浏览了文档,却没有发现任何东西。


2
只是鼠标悬停。
dfsq,2016年


1
我认为mousemove活动也可以为您提供帮助。请参阅此页面示例
Abhi,

Answers:


216

如果要在任何HTML元素上执行类似悬停事件,则可以这样做。

的HTML

 <div (mouseenter) ="mouseEnter('div a') "  (mouseleave) ="mouseLeave('div A')">
        <h2>Div A</h2>
 </div> 
 <div (mouseenter) ="mouseEnter('div b')"  (mouseleave) ="mouseLeave('div B')">
        <h2>Div B</h2>
 </div>

零件

import { Component } from '@angular/core';

@Component({
    moduleId: module.id,
    selector: 'basic-detail',
    templateUrl: 'basic.component.html',
})
export class BasicComponent{

   mouseEnter(div : string){
      console.log("mouse enter : " + div);
   }

   mouseLeave(div : string){
     console.log('mouse leave :' + div);
   }
}

您应该同时使用mouseenter和mouseleave事件,以便在角度2中实现功能齐全的悬停事件。


如何从角度分量.ts文件触发它?
Mayur kukadiya

@mayurkukadiya见下面我的更新答案- stackoverflow.com/a/37688325/5043867
Pardeep耆那

117

是的,on-mouseover在angular2中有而不是ng-Mouseover在angular 1.x中,所以您必须编写以下内容:

<div on-mouseover='over()' style="height:100px; width:100px; background:#e2e2e2">hello mouseover</div>

over(){
    console.log("Mouseover called");
  }

正如@Gunter在评论中建议的那样,on-mouseover我们也可以使用它。有些人更喜欢前缀上的替代形式,即规范形式。

更新资料

HTML代码-

<div (mouseover)='over()' (mouseout)='out()' style="height:100px; width:100px; background:#e2e2e2">hello mouseover</div>

控制器/.TS代码-

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';

  over(){
    console.log("Mouseover called");
  }

  out(){
    console.log("Mouseout called");
  }
}

工作实例

可以在Angular中使用其他一些Mouse事件-

(mouseenter)="myMethod()"
(mousedown)="myMethod()"
(mouseup)="myMethod()"

47
为什么不<div (mouseover)='over()'呢?;-)
君特Zöchbauer

2
@GünterZöchbauer,他们是所有活动的清单吗?我看了看2
号角

5
这些不是Angular事件,而是浏览器事件。
君特Zöchbauer

1
显然,这就是方法,但是是否有人为此提供了Angular文档的链接?我觉得它超级抽象而且稀疏。我只是在寻找清单,所以我知道标准是什么。
ThePartyTurtle

35

您可以通过主机进行操作:

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;
  }

}

只需将其适应您的代码即可(位于:https : //angular.io/docs/ts/latest/guide/attribute-directives.html


18

如果您对鼠标进入或离开组件之一感兴趣,则可以使用@HostListener装饰器:

import { Component, HostListener, OnInit } from '@angular/core';

@Component({
  selector: 'my-component',
  templateUrl: './my-component.html',
  styleUrls: ['./my-component.scss']
})
export class MyComponent implements OnInit {

  @HostListener('mouseenter') 
  onMouseEnter() {
    this.highlight('yellow');
  }

  @HostListener('mouseleave') 
  onMouseLeave() {
    this.highlight(null);
  }

...

}

如@Brandon注释中链接到OP所述(https://angular.io/docs/ts/latest/guide/attribute-directives.html


10

简单地做 (mouseenter)在Angular2 +中属性...

在HTML中执行以下操作:

<div (mouseenter)="mouseHover($event)">Hover!</div> 

并在您的组件中执行以下操作:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'component',
  templateUrl: './component.html',
  styleUrls: ['./component.scss']
})

export class MyComponent implements OnInit {

  mouseHover(e) {
    console.log('hovered', e);
  }
} 

7

为了处理overing事件,您可以尝试执行以下操作(对我有用):

在HTML模板中:

<div (mouseenter)="onHovering($event)" (mouseleave)="onUnovering($event)">
  <img src="../../../contents/ctm-icons/alarm.svg" class="centering-me" alt="Alerts" />
</div>

在角度分量中:

    onHovering(eventObject) {
    console.log("AlertsBtnComponent.onHovering:");
    var regExp = new RegExp(".svg" + "$");

    var srcObj = eventObject.target.offsetParent.children["0"];
    if (srcObj.tagName == "IMG") {
        srcObj.setAttribute("src", srcObj.getAttribute("src").replace(regExp, "_h.svg"));       
    }

   }
   onUnovering(eventObject) {
    console.log("AlertsBtnComponent.onUnovering:");
    var regExp = new RegExp("_h.svg" + "$");

    var srcObj = eventObject.target.offsetParent.children["0"];
    if (srcObj.tagName == "IMG") {
        srcObj.setAttribute("src", srcObj.getAttribute("src").replace(regExp, ".svg"));
    }
}

6

如果将鼠标悬停在整个组件上,则可以选择直接@hostListener处理事件以在下面的所有组件上进行鼠标悬停。

  import {HostListener} from '@angular/core';

  @HostListener('mouseenter') onMouseEnter() {
    this.hover = true;
    this.elementRef.nativeElement.addClass = 'edit';
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.hover = false;
    this.elementRef.nativeElement.addClass = 'un-edit';
  }

它在中可用@angular/core。我对它进行了角度测试4.x.x


2
@Component({
    selector: 'drag-drop',
    template: `
        <h1>Drag 'n Drop</h1>
        <div #container 
             class="container"
             (mousemove)="onMouseMove( container)">
            <div #draggable 
                 class="draggable"
                 (mousedown)="onMouseButton( container)"
                 (mouseup)="onMouseButton( container)">
            </div>
        </div>`,

})

http://lishman.io/angular-2-event-binding


1

在您将要悬停的html的js / ts文件中

@Output() elemHovered: EventEmitter<any> = new EventEmitter<any>();
onHoverEnter(): void {
    this.elemHovered.emit([`The button was entered!`,this.event]);
}

onHoverLeave(): void {
    this.elemHovered.emit([`The button was left!`,this.event])
}

在将要悬停的HTML中

 (mouseenter) = "onHoverEnter()" (mouseleave)="onHoverLeave()"

在您的js / ts文件中,它将接收到悬停信息

elemHoveredCatch(d): void {
    console.log(d)
}

在与捕获的js / ts文件相关的HTML元素中

(elemHovered) = "elemHoveredCatch($event)"
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.