Angular 2: Can focusin and focusout be in one event?

Char picture Char · Jun 23, 2017 · Viewed 54.1k times · Source

Can focusin and focusout be in one event? What is it called, then? If not, is there a way to merge this in one function?

Answer

Mr_Perfect picture Mr_Perfect · Jun 23, 2017

First thing is you need to add tabindex attribute to section to make it to get focus event. Otherwise, it won't get focus event.

Focus event get triggered when an element is focus-able. Every time you click the element it is always get focused and we can remove the focus only on click outside the element. So, we can't remove focus on click event of the same element.

focus and focusout both are different events we can't merge them

You can use *ngIf also

<section 
    class="search-bar-wrapper" 
    tabindex="-1" 
    (focus)="show($event)" 
    (focusout)="hide($event)"
>

<div class="suggestion" *ngIf="canSee">
    This is a suggestion
</div>

in the class of the component

casSee: boolean = false;

show(e: any) {
   this.canSee = true;
}

hide(e: any) {
   this.canSee = false;
}