javascripthtmlangulartypescriptmouseevent

Angular: Prevent BLUR event when CLICK event happens


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.

issue blur/click

Here is a stackblitz example I've created.


Solution

  • 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