Reputation: 717
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?
Upvotes: 1
Views: 1915
Reputation: 717
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
Upvotes: 2