1

The below problem is related to Blur not working - Angular 2 thread.

I have a shared component of custom select and I am trying to add a blur event to close when the component is not in focus.

// HTML

<div (blur)="closeDropDown()" tabindex="0">
  <span (click)="selectClicked()" class="placeholder">
    Select Item 
  </span>
  <div class="options">
    <ul>
       <li *ngFor="let item of data"> 
       <span>{{item}}</span></li>
    </ul>
  </div>

//TS

 selectClicked() {
   this.dropdownOpen = true;
 }

 closeDropDown() {
   this.dropdownOpen = false;
 }

I was able to implement the blur event by adding the tabindex mentioned in the thread(works in all browsers except IE). But blur event is not firing in IE(version > 10).

I tried to use focusout instead of blur but the selected value is not getting attached to the custom select and requires many selections to select an option.

Why does blur is not triggering on div and are there any alternatives that I can use on block level elements?

Onera
  • 687
  • 3
  • 14
  • 34
  • I suggest you to try to make a test with any other event to check whether the issue can be produce with any event or the issue is specifically with this event. It can be possible that any events is not calling in IE. For testing purpose, try to remove tabindex="0" and try to check whether event is working in IE or not. – Deepak-MSFT Jul 31 '19 at 14:33
  • I'm sorry, but I kinda cringe when I see people trying to rewrite an existing HTML element. in this case, looks like you're trying to rewrite the select. when dealing with select for example, have you considered accessibility ? are the users using screen-readers, able to hear the option they're currently selecting ? what happens when they press tab ? shift tab ? side arrow ? esc ? is RTL supported ? Browsers devs had whole teams that did an extensive research, met known standards and thought about edge cases. do you really think you can do better on your own ? do you really want to ? – Stavm Aug 02 '19 at 07:25

1 Answers1

2

I was able to fix the problem by adding focusout and tabindex=-1 to a div element. But by doing this value was not getting set to my custom dropdown.

The reason for that is when I used focusout, the event was bubbling back to parent and took more time to set the dropdown value after selection.

So I missed to stop the bubbling event, the fix was to stop the propogation.

// html
<div (focusout)="closeDropDown($event)" tabindex="-1"></div>

// ts
closeDropDown(event) {
  event.stopPropogation();
  this.dropdownOpen = false;
}

The focusout event fires when an element is about to lose focus. The main difference between this event and blur is that focusout bubbles while blur does not.

Find more about this on blur vs focusout -- any real differences? and https://developer.mozilla.org/en-US/docs/Web/API/Element/focusout_event

Onera
  • 687
  • 3
  • 14
  • 34