Ionic框架如何实现长按事件?

3

在TypeScript中是否可以将一个按钮分配给“按住点击”事件?

例如:

<button ion-button icon-only color="royal" (click)="addNote()" (holdclick)="removeNote()">
1个回答

10
你可以使用 press 事件(更多信息请参阅手势文档):
import { Component } from '@angular/core';

@Component({
  templateUrl: 'template.html'
})
export class BasicPage {

  public press: number = 0;

  constructor() {}

  pressEvent(e) {
    this.press++
  }

}

并且在视图中:

  <ion-card (press)="pressEvent($event)">
    <ion-item>
      Pressed: {{press}} times
    </ion-item>
  </ion-card>

如果这还不够(也许您的场景需要更长的按压事件),则可以通过创建自定义指令来创建自己的手势事件。更多信息可以在这篇由Roblouie撰写的精彩文章中找到。该文章使用了旧版本的Ionic,但主要思想仍然相同(并且几乎所有代码都应该像原样工作)。
import {Directive, ElementRef, Input, OnInit, OnDestroy} from '@angular/core';
import {Gesture} from 'ionic-angular';

@Directive({
  selector: '[longPress]'
})
export class PressDirective implements OnInit, OnDestroy {
  el: HTMLElement;
  pressGesture: Gesture;

  constructor(el: ElementRef) {
    this.el = el.nativeElement;
  }

  ngOnInit() {
    this.pressGesture = new Gesture(this.el, {
      recognizers: [
        [Hammer.Press, {time: 6000}] // Should be pressed for 6 seconds
      ]
    });
    this.pressGesture.listen();
    this.pressGesture.on('press', e => {
      // Here you could also emit a value and subscribe to it
      // in the component that hosts the element with the directive
      console.log('pressed!!');
    });
  }

  ngOnDestroy() {
    this.pressGesture.destroy();
  }
}

然后在你的html元素中使用它:

<button longPress>...<button>

1
太厉害了。这让“Android开发者模式”通过按10次关于按钮的想法/功能变得如此简单。谢谢。 - vr_driver
这是我的完整示例。https://stephenmonro.wordpress.com/2019/10/29/secret-menu-in-an-ionic-app/ - vr_driver

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接