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

前端 未结 1 1145
梦毁少年i
梦毁少年i 2021-02-06 08:48

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

But how does this work in Angular 2?

相关标签:
1条回答
  • 2021-02-06 09:30

    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.

    0 讨论(0)
提交回复
热议问题