如何在Angular 2中监听并按住? [英] How to listen for a click-and-hold in Angular 2?

查看:79
本文介绍了如何在Angular 2中监听并按住?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此链接中 ,您可以在AngularJS中找到一个示例.

In this link, you can find an example in AngularJS.

但是这在Angular 2中如何工作?

But how does this work in Angular 2?

推荐答案

一个简单的实现如下所示.

A simple implementation would look like this.

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2 (mousedown)="mousedown()" (mouseup)="mouseup()" (mouseleave)="mouseup()">Hello {{name}}</h2>
    </div>
  `,
})
export class App {
  name: string;
  timeoutHandler: number;

  constructor() {
    this.name = 'Angular!'
  }
  public mouseup() {
    if (this.timeoutHandler) {
      clearTimeout(this.timeoutHandler);
      this.name = "canceled";
      this.timeoutHandler = null;
    }
  }

  public mousedown() {
    this.timeoutHandler = setTimeout(() => {
      this.name = "has been long pressed"
      this.timeoutHandler = null;
    }, 500);
  }
}

它设置了一个超时,如果用户在设置的时间之前单击离开,则该超时将被取消.

It sets a timeout that is canceled if the user clicks away before a set amount of time.

您可以在此处找到工作的plnkr.

You can find a working plnkr here.

如果您想要的是在单击保持状态时发生某些事情,这也很容易做到,只需将setTimeout替换为setInterval.

If what you want is for something to happen on click on hold it's pretty easy to do as well, just swap setTimeout for setInterval.

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2 (mousedown)="mousedown()" (mouseup)="mouseup()" (mouseleave)="mouseup()">Hello {{name}}</h2>
    </div>
  `,
})
export class App {
  name: number = 0;
  timeoutHandler;

  constructor() {
    this.name = -1
  }
  public mouseup() {
    if (this.timeoutHandler) {
      clearInterval(this.timeoutHandler);
      this.name = 0;
      this.timeoutHandler = null;
    }
  }

  public mousedown() {
    this.timeoutHandler = setInterval(() => {
      this.name += 1;
    }, 100);
  }
}

可以在此处找到工作的plnkr.

A working plnkr can be found here.

这篇关于如何在Angular 2中监听并按住?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆