Setting focus on mat button dynamically not working

Issue

In my application I have an input field where user can enter the city code and on focus out service will be called to get the City details and search button will be enabled and focused . When the user enter the city code and tab out everything works as expected but the focus is not been set to Search button. I understand that disabled buttons will not receive focus event but am setting focus only after enabling the button but it still doesn’t seem to work .

Ts

export class InputErrorsExample {
  city = new FormControl('');
  search: boolean = false;

  fetchCityDetails() {
    setTimeout(() => {
      // calling service to fetch details
      this.search = true;
      let btn = document.getElementById('search');
      if (btn) btn.focus();
    }, 1000);
  }
}

HTML

<form class="example-form">
  <mat-form-field class="example-full-width" appearance="fill">
    <mat-label>City</mat-label>
    <input type="text" matInput [formControl]="city" (focusout)="fetchCityDetails()">

  </mat-form-field>

  <button tabindex="0" id="search"  mat-raised-button color="primary" [disabled] = "!search">Search</button>

</form>

Here is the link for stackblitz https://stackblitz.com/edit/angular-ymkvhp?file=src%2Fapp%2Finput-errors-example.html .

Solution

Try delay the focus of button with another setTimeout

 fetchCityDetails() { 
    setTimeout(() => {
      // calling service to fetch details
      this.search = true;
      setTimeout(()=>{
        let btn = document.getElementById('search');
        if (btn) btn.focus();
      })
    }, 1000);
  }

Answered By – Chellappan வ

Answer Checked By – Candace Johnson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.