Search code examples
javascriptangularinputonbluronfocus

angular onblur works incorrectly when clicking input in div


I'm giving a tabindex to the div and closing the div with on blur but when I click on the input inside the div, the div closes. How can I solve this?

app.component.html

<button (click)="openToggle('toggle1')">Toggle 1</button>
<button (click)="openToggle('toggle2')">Toggle 2</button>

<div
  *ngIf="selectedToggle === 'toggle1'"
  tabindex="0"
  (blur)="closeToggle()"
  class="menu"
>
  Toggle 1
</div>

<div
  *ngIf="selectedToggle === 'toggle2'"
  tabindex="1"
  (blur)="closeToggle()"
  class="menu"
>
  <input type="text" />
</div>

app.component.ts

  public selectedToggle = '';

  public openToggle(e: string) {
    this.selectedToggle = e;
  }

  public closeToggle() {
    this.selectedToggle = '';
  }

Solution

  • That's expected, when you click in the input, the focus shift from the div to the input thus firing the blur event on the div.