Angular 2 right click events?

后端 未结 1 2014
北海茫月
北海茫月 2020-12-16 10:20

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 con

相关标签:
1条回答
  • 2020-12-16 10:47

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

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

    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.

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

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

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