How to make disable right click function in angular called from any component

Viewed 17573
<div class="container" (contextmenu)="onRightClick()">
</div>

I want to disable right click in a few components and not the whole website. I have to define the below function in all the components where I want to disable right click. What's the best way to do it so that I don't have to define the function again and again in those components

onRightClick() {
  return false;
}
5 Answers

It's the contextmenu event : create a directive to manage that.

Stackblitz

@HostListener('contextmenu', ['$event'])
onRightClick(event) {
  event.preventDefault();
}

My advice is to make a directive that will have click binded to element where it is attached. You got small tutorial on their official documentation and it should give you clear path on what you should make.

In this case, you can reuse directive all over your app and will do just the same thing. Will bind click to element where it is attached and will have some logic in it, so you don't repeat yourself.

doc

Example:

import { Directive, HostListener } from '@angular/core';

@Directive({
  selector: '[appDisableRightClick]'
})
export class DisableRightClickDirective {
  @HostListener('contextmenu', ['$event'])
  onRightClick(event) {
    event.preventDefault();
  }
}

you can also make module that will export this directive and in order to use it in your other modules, just import that module. Modules should look like the following:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DisableRightClickDirective } from './disable-right-click.directive';

@NgModule({
  declarations: [
    DisableRightClickDirective
  ],
  imports: [
    CommonModule
  ],
  exports: [
    DisableRightClickDirective
  ]
})
export class DisableRightClickModule {
}

In every module, where you'd like to use this directive, all you have to do is import DisableRightClickModule. And that's pretty much it.

import { NgModule } from '@angular/core';
import { DisableRightClickModule } from './disable-right-click.module';

@NgModule({
  declarations: [
   ...
  ],
  imports: [
    ....,
    DisableRightClickModule
  ]
})
export class SomeDummyModule {
}

Inside your HTML just attach directive to any element as attribute eg.

<a href="#" appDisableRightClick>

you can easily do like below:

<div class="container" (contextmenu)="onRightClick()"></div>
onRightClick(event) {
  event.preventDefault();
}

note: this code only disable right click for the div you referred. If you want to disable for all page you can use:

@HostListener('contextmenu', ['$event'])
  onRightClick(event) {
  event.preventDefault();
}

If you are interested to disable right click on entire Angular app, use below in index.html file.
<body class="mat-typography" oncontextmenu="return false">

It worked for me without Hostistner. (contextmenu)="$event?.preventDefault();"

Related