Angular 2右键单击事件? [英] Angular 2 right click events?

查看:128
本文介绍了Angular 2右键单击事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Angular2构建一个交互式Web应用程序,并且正在寻找一种捕获角度组件上的右键单击的方法.我还需要防止右键单击时显示浏览器上下文菜单,以便显示自己的自定义上下文菜单.

I am building an interactive web application with Angular2 and I am looking for a way to capture right clicks on an angular component. I also need to prevent the browser context menu appearing on a right click so I can display my own custom context menu.

我知道在角度1中,您必须创建一个自定义指令来捕获右键单击事件. Angular 2仍然是这种情况吗,还是内置于其中/是否有更简单的方法呢?我已经看过以前的一些SO问题,但它们与Angular2没有关系.

I know that in angular 1, you had to create a custom directive to capture a right click event. Is this still the case in Angular 2, or is it built in/is there an easier way of doing it? I've had a look through some previous SO questions but they do not relate to Angular2.

如何完成捕获右键单击并阻止浏览器上下文菜单出现在Angular2中的功能?

How can I accomplish capturing right clicks and preventing the browser context menu from appearing in Angular2?

推荐答案

在Angular 2+中,您可以捕获任何事件,例如:

In Angular 2+, you can capture any event like:

<div (anyEventName)="whateverEventHandler($event)">
</div>

请注意,$event是可选的,函数的返回就是事件处理程序的返回,因此,您可以return false;避免事件发生默认的浏览器操作.

Note that $event is optional, and the return of the function is the return of the event handler, so, you can return false; to avoid default browser action from the event.

在您的情况下,事件名称为contextmenu.因此,您的代码可以是这样的:

In your case the event name is contextmenu. So, your code can be something like this:

@Component({
  selector: 'my-app',
  template: `
    <div (contextmenu)="onRightClick($event)">
      Right clicked
      {{nRightClicks}}
      time(s).
    </div>
  `,
  // Just to make things obvious in browser
  styles: [`
    div {
      background: green;
      color: white;
      white-space: pre;
      height: 200px;
      width: 200px;
    }
  `]
})
export class App {
  nRightClicks = 0;

  constructor() {
  }

  onRightClick() {
    this.nRightClicks++;
    return false;
  }
}

这是一个完整的工作示例:
http://on.gurustop.net/2E0SD8e

Here's a full working example:
http://on.gurustop.net/2E0SD8e

这篇关于Angular 2右键单击事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆