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

I'm writing an Angular app where there is a scenario I've to prevent blur event when click ev

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744257911a4565487.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信