Angular 角度:如何在ngbDropdown菜单中聚焦输入?
我试图使用ElementRef来关注输入。除了在ng引导库的下拉列表中之外,这一切都很好。如何在一个特定的时间内触发事件 例如: 组件类 从'@angular/core'导入{Component,ViewChild,ElementRef}; @组成部分{ 选择器:“ngbd下拉菜单基本”, templateUrl:“./dropdown basic.html” } 导出类NgbdDropdownBasic{ @ViewChildsearch搜索字段:ElementRef; @ViewChildsearchOutside searchFieldOutside:ElementRef; onToggledropDownOpen:布尔值{ 如果下拉打开{ this.searchField.nativeElement.focus; } } 聚焦其他场{ this.searchFieldOutside.nativeElement.focus; } } 组件模板 示例1:内部下拉列表不工作 切换下拉列表 示例2:外部下拉列表 关注这一领域:Angular 角度:如何在ngbDropdown菜单中聚焦输入?,angular,ng-bootstrap,Angular,Ng Bootstrap,我试图使用ElementRef来关注输入。除了在ng引导库的下拉列表中之外,这一切都很好。如何在一个特定的时间内触发事件 例如: 组件类 从'@angular/core'导入{Component,ViewChild,ElementRef}; @组成部分{ 选择器:“ngbd下拉菜单基本”, templateUrl:“./dropdown basic.html” } 导出类NgbdDropdownBasic{ @ViewChildsearch搜索字段:ElementRef; @ViewChilds
问题是,在单击下拉列表并调用onToggle时,DOM尚未更新以呈现下拉列表和下拉列表中的输入 您可以通过构造函数将ChangeDetectorRef注入组件:
import { ChangeDetectorRef } from '@angular/core';
...
export class NgbdDropdownBasic {
...
constructor(private _cdRef: ChangeDetectorRef) {}
并称之为.\u cdRef.detectChanges;在关注onToggle方法中的输入之前:
这将导致下拉列表和输入被呈现,因此当您调用This.searchField.nativeElement.focus时;它已经可见并将获得焦点
请参阅以获得有效演示。将z顺序更改为10左右。您不能将注意力集中在不在顶部的元素上。
onToggle(dropDownOpen: boolean) {
if (dropDownOpen) {
this._cdRef.detectChanges();
this.searchField.nativeElement.focus();
}
}