Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

But how does this work in Angular 2?

like image 243
Franz Peter Tebartz van Elst Avatar asked Mar 28 '17 13:03

Franz Peter Tebartz van Elst


1 Answers

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.

like image 150
toskv Avatar answered Oct 17 '22 02:10

toskv