简体   繁体   English

如何将焦点设置在 ViewChildren QueryList 的第一个元素上?

[英]How to set focus on the first element of a ViewChildren QueryList?

Objective I have a search button that returns an API response of books.目标我有一个搜索按钮,它返回书籍的 API 响应。 After the search button is clicked, Angular/JavaScript should set focus on the first element from a ViewChildren QueryList.单击搜索按钮后,Angular/JavaScript 应该将焦点设置在 ViewChildren QueryList 中的第一个元素上。

Template:模板:

<form [formGroup]="searchForm" (submit)="searchBooks()">
  <mat-form-field>
    <input matInputformControlName="term"/>
    <button aria-label="Search" mat-icon-button matSuffix>
      <mat-icon>search</mat-icon>
    </button>
  </mat-form-field>
</form>

<ng-container *ngIf="books$ | async as books">
    <div class="book" *ngFor="let book of books">
      <div #bookItem tabindex="-1">
        {{ book.title }}
      </div>
     ...
</ng-container>

Component:零件:

export class AppComponent {
  @ViewChildren('bookItem') bookItem: QueryList<ElementRef>;
      searchBooks() {
        if (this.searchForm.value.term) {
          this.store.dispatch(searchBooks({ term: this.searchTerm })); // fetches books from an API
          this.bookItem.first.nativeElement.focus() // what I thought would work
         } 
      }

When I try to set focus I get the following error:当我尝试设置焦点时,出现以下错误:

Cannot read property 'nativeElement' of undefined无法读取未定义的属性“nativeElement”

I'm thinking this could be because of the asynchronous nature of fetching books from an API.我认为这可能是因为从 API 获取书籍的异步性质。 Any idea on how to set focus to the first element of a ViewChildren list?关于如何将焦点设置到 ViewChildren 列表的第一个元素的任何想法?

this.bookItem.get(0).focus() or this.bookItem.first.focus() will set the focus for the first element of Viewchildren list. this.bookItem.get(0).focus()this.bookItem.first.focus()将为 Viewchildren 列表的第一个元素设置焦点。

I suggest subscribe to bookItem.changes like this SO我建议像这样订阅 bookItem.changes

If you don't want make it at very early use a variable "yet" at first value=false and in searchBook equal true如果您不想在很早的时候使用它,请在第一个 value=false 和 searchBook 中使用变量“yet”等于 true

  ngAfterViewInit()
  {
     this.inputs.changes.subscribe(res=>{
       if (this.yet && res.length)
        res.first.nativeElement.focus()
     })
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM