如何在Angular 2中收听点击并按住?

时间:2017-03-28 13:38:48

标签: angular typescript

In this link,你可以在AngularJS中找到一个例子。

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

1 个答案:

答案 0 :(得分:8)

一个简单的实现看起来像这样。

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

如果用户在设定的时间内点击了它,则会设置取消超时。

你可以找到一个有效的plnkr here

如果你想要的是点击保持它会发生什么事情也很容易做,只需将setTimeout换成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 here