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.
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.
blurEvent(event: any) {
if (!event?.relatedTarget?.classList?.contains('skip-blur')) {
this.inputField = 'Blur occured';
}
}
<h1>Hello from {{ name }}!</h1>
<div>
<input (blur)="blurEvent($event)" [(ngModel)]="inputField" />
<button class="skip-blur" (click)="clickEvent()">Clear</button>
</div>