angular - 如何在 Angular 2 中监听点击并按住?

标签 angular typescript

In this link ,您可以在 AngularJS 中找到示例。

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

最佳答案

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

@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 .

关于angular - 如何在 Angular 2 中监听点击并按住?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43071160/

相关文章:

angular - Material Design Lite 和 Angular Material Design 有什么区别?

excel - 如何从 Excel 工作表或其他文件创建 cucumber 特征文件

reactjs - TS2339 : Property 'focus' does not exist on type '{}' . 与 React typescript

javascript - 跨多个文件将大型 typescript 文件拆分为模块

javascript - 我可以在常规 JS 中监听 AngularJS 中抛出的事件吗(在 Angular 之外?)

typescript - 捆绑和使用 webpack 构建的 typescript 库的正确方法?

angular - primeng下拉列表不显示

java - 部署 Angular 5 Spring Boot 多模块项目-jar

Angular 6 : Unable to set Content-Type of http Header correctly

Angular 2 : Import service based on environment