javascript - Angular: Prevent BLUR event when CLICK event happens - Stack Overflow

admin2025-04-10  0

I'm writing an Angular app where there is a scenario I've to prevent blur event when click event happens. Problem is I'm not able to understand how this will happen as on click blur will always trigger since the target element is not in focus.

Is there any way I can achieve this? Below is a video of what is happening. You will notice that 1st the BLUR event is completed then the click event on click of Clear button.

Here is a stackblitz example I've created.

I'm writing an Angular app where there is a scenario I've to prevent blur event when click event happens. Problem is I'm not able to understand how this will happen as on click blur will always trigger since the target element is not in focus.

Is there any way I can achieve this? Below is a video of what is happening. You will notice that 1st the BLUR event is completed then the click event on click of Clear button.

Here is a stackblitz example I've created.

Share Improve this question edited Mar 24 at 6:41 Naren Murali 60.2k5 gold badges44 silver badges77 bronze badges asked Mar 24 at 6:28 avishekdravishekdr 1,0822 gold badges34 silver badges65 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

You can get the blur event ($event as an argument to the method), then check for relatedTarget - MDN Docs property to not be the button and skip the actions. Here I added a class to identify the button where the blur event should be skipped.

TS:

blurEvent(event: any) {
  if (!event?.relatedTarget?.classList?.contains('skip-blur')) {
    this.inputField = 'Blur occured';
  }
}

HTML:

<h1>Hello from {{ name }}!</h1>
<div>
  <input (blur)="blurEvent($event)" [(ngModel)]="inputField" />&nbsp;
  <button class="skip-blur" (click)="clickEvent()">Clear</button>
</div>

Stackblitz Demo

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1744257913a238404.html

最新回复(0)