How to listen for a click-and-hold in Angular 2?

2020-06-04 10:56发布

问题:

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

But how does this work in Angular 2?

回答1:

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.

You can find a working plnkr here.

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

A working plnkr can be found here.