【问题标题】:set focus on button whenever it gets enabled启用按钮时将焦点设置在按钮上
【发布时间】:2021-09-05 10:11:57
【问题描述】:

在我的 Angular 8 应用程序中,我试图在 mat 按钮启用后立即将其设置为焦点。启用按钮在收到服务响应并验证几个条件后发生。 Setting focus on mat button dynamically not working 是我的老问题。 但是由于某种原因,当我在原始代码中使用它时它不起作用。因此,我正在寻找诸如自动对焦指令之类的选项,该指令可以在启用按钮时设置焦点。有没有可能实现?

【问题讨论】:

    标签: angular typescript autofocus


    【解决方案1】:

    通过对 Beka 提供的答案进行以下修改,我能够将焦点设置在按钮上

    export class InputErrorsExample {
    
      @ViewChild('search', {read: ElementRef, static: false}) btn: ElementRef;   // to access button in ts
      city = new FormControl('');
      search: boolean = false;
    
      constructor(private http: HttpClient) {}
    
      fetchCityDetails() {
        this.http
          .get('https://countriesnow.space/api/v0.1/countries/population/cities')
          .subscribe(data => {
            if (data) {
              this.btn.nativeElement.disabled = false ;
              this.btn.nativeElement.focus();
            }
          });
      }
    }
    

    【讨论】:

      【解决方案2】:

      你可以ViewChild你的按钮元素:

      export class InputErrorsExample {
        @ViewChild('search', { static: true }) btn: HTMLButtonElement;
        city = new FormControl('');
        search: boolean = false;
      
        constructor(private http: HttpClient) {}
      
        fetchCityDetails() {
          this.http
            .get('https://countriesnow.space/api/v0.1/countries/population/cities')
            .subscribe(data => {
              if (data) {
                this.search = true;
                this.btn.focus();
              }
            });
        }
      }
      

      但您还必须在 HTML 中给出正确的标签 #search

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

      【讨论】:

      • 感谢您的回复。当我保持静态时:true 它会引发未定义的错误
      猜你喜欢
      • 2021-05-21
      • 2011-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-19
      相关资源
      最近更新 更多