Angular:如何在 ngbDropdown 菜单中聚焦输入?

Angular: How do you focus an input inside a ngbDropdown Menu?

我正在尝试使用 ElementRef 来关注输入。这工作正常,除了在 ng-bootstrap 库的下拉列表中。如何在 ngbDropdown 中触发事件?

示例:https://stackblitz.com/edit/angular-z7q9xm

组件class

import { Component, ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'ngbd-dropdown-basic',
  templateUrl: './dropdown-basic.html'
})
export class NgbdDropdownBasic {
  @ViewChild("search") searchField: ElementRef;
  @ViewChild("searchOutside") searchFieldOutside: ElementRef;

  onToggle(dropDownOpen: boolean) {
    if (dropDownOpen) {
      this.searchField.nativeElement.focus();
    }
  }

  focusOtherField() {
    this.searchFieldOutside.nativeElement.focus();
  }
}

组件模板

<div class="row">
  <div class="col"><h3>Example 1: Inside dropdown <br>(not working)</h3></div>
</div>
<div class="row form-group">
  <div class="col">
    <div ngbDropdown (openChange)="onToggle($event)" class="d-inline-block">
      <button class="btn btn-outline-primary" id="dropdownBasic1" ngbDropdownToggle>Toggle dropdown</button>
      <div ngbDropdownMenu aria-labelledby="dropdownBasic1">
        <div class="p-2"><input #search name="search" class="form-control" placeholder="Search..."></div>
      </div>
    </div>
  </div>
</div>
<hr>
<div class="row">
  <div class="col"><h3>Example 2: Outside dropdown</h3></div>
</div>
<div class="row form-group">
  <div class="col-auto"><button (click)="focusOtherField()" type="button" class="btn btn-outline-primary">Focus this field:</button></div>
    <div class="col">
    <input #searchOutside name="searchOutside" class="form-control" placeholder="Search...">
  </div>
</div>

问题是在单击下拉菜单并调用 onToggle 时,DOM 尚未更新以呈现下拉菜单和下拉菜单中的输入。

你可以做的是通过构造函数将 ChangeDetectorRef 注入到组件中:

import { ChangeDetectorRef } from '@angular/core';
...

export class NgbdDropdownBasic {
  ...
  constructor(private _cdRef: ChangeDetectorRef) {}

并调用 this._cdRef.detectChanges();,然后再关注 onToggle 方法中的输入:

onToggle(dropDownOpen: boolean) {
  if (dropDownOpen) {
    this._cdRef.detectChanges();
    this.searchField.nativeElement.focus();
  }
}

这将导致呈现下拉菜单和输入,因此当您调用 this.searchField.nativeElement.focus(); 时它已经可见并获得焦点。

请参阅 this StackBlitz 的工作演示。