AJ-
AJ-

Reputation: 1783

Angular - How to disable mouse click events outside a specific DIV based on a condition?

I'm using a RAD tool that generates angular code, and I want to make some modifications to a specific behaviour.

I have a grid and I can enter "edit" mode for a specific row with a button click, now once in edit mode, I want to disable completely mouse clicks outside the div containing that grid, because if the users clicks on some components outside the grid, before saving his edit, it will cause some bugs.

So I when the "Edit" button is clicked, I want to stop mouse events outside a specific div, and as soon as the "Save" button is clicked, I want to allow again mouse events everywhere.

I have no code to show, as it would be just some html code with some buttons tags.

The solution I'm looking for is just to know what is the correct way to do this, then I Can implement it by myself

Upvotes: 0

Views: 6104

Answers (3)

Mariano Calcagno
Mariano Calcagno

Reputation: 420

If i understood, you want to stop propagation only outside the div... So if you click in div, the click has effects; else the propagation will stopped. You need to use HostListener (here the official documentation https://angular.io/api/core/HostListener)

Try in this way:

<div #myDIVName (click)="stopEvent($event)"></div>

and in your component, declare a variable with the ViewChild decorator

@ViewChild('myDIVName') myDIVName;

and add this function

@HostListener('document:click', ['$event'])
  public onClick(event) {
    try {
      if (this.disableOutsideClick &&   !this.myDIVName.nativeElement.contains(event.target)) {
        event.stopPropagation():
        }
    } catch (e) {
        console.log(e);
        }
    }

Upvotes: 0

Peter Simpkins
Peter Simpkins

Reputation: 1

If you pass the event into your method, you can call stopPropagation to prevent it falling through to the elements behind it;


    (click)="myMethod($event)"

    myMethod(event: any){
      event.stopPropagation();
      ...
    }

Alternatively you can call stopPropagation right on the template


    (click)="myMethod(); $event.stopPropagation()"

You can make this conditional by combining it with whatever variable you have to set edit mode, i.e.

    this.editMode && event.stopPropagation()

Upvotes: 0

Ling Vu
Ling Vu

Reputation: 5181

You can do the following thing. Look at the code and find the (click) event and pass the reference of the MouseEvent to this event.

Template:

<div (click)="stopEvent($event)"></div>

Then call:

stopEvent(e: MouseEvent) {
  e.stopPropagation();
}

Another solution would be to add a disable to the div tag:

<div [disabled]="true"></div>

Upvotes: 2

Related Questions