【问题标题】:Setting focus on mat button dynamically not working动态设置对垫子按钮的关注不起作用
【发布时间】:2021-11-02 12:51:24
【问题描述】:

在我的应用程序中,我有一个输入字段,用户可以在其中输入城市代码,然后将调用聚焦服务以获取城市详细信息,并且搜索按钮将被启用和聚焦。当用户输入城市代码并标记出所有内容时,一切都按预期工作,但焦点未设置为“搜索”按钮。我知道禁用的按钮不会收到焦点事件,但只有在启用按钮后才设置焦点,但它似乎仍然不起作用。

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>

这里是 stackblitz https://stackblitz.com/edit/angular-ymkvhp?file=src%2Fapp%2Finput-errors-example.html 的链接。

【问题讨论】:

    标签: angular typescript button angular-material focus


    【解决方案1】:

    尝试用另一个 setTimeout 延迟按钮的焦点

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

    【讨论】:

    • 非常感谢您的回复。但是由于某种原因,当我尝试使用原始代码时它不起作用。按钮在获得服务响应后启用,并且还基于几个条件。我需要按钮在启用后立即聚焦。你能帮忙吗?
    • 你能分享一些代码示例吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-08
    • 1970-01-01
    • 1970-01-01
    • 2016-01-22
    相关资源
    最近更新 更多