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

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>

Tags:

Angular