要使Angular ngbDropdown的键盘导航正常工作,你需要在templateRef和ngbDropdown实例之间使用ng-container指令来设置tabindex,然后使用@ViewChild装饰器引用ngbDropdown指令,最后在NgAfterViewInit生命周期钩子中调用dropdown.focusFirst()方法即可。
HTML模板:
组件类:
import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { NgbDropdown } from '@ng-bootstrap/ng-bootstrap';
@Component({
selector: 'app-dropdown-example',
templateUrl: './dropdown-example.component.html'
})
export class DropdownExampleComponent implements AfterViewInit {
dropdownItems = [
'Action',
'Another action',
'Something else is here'
];
@ViewChild('myDrop', { static: false }) dropdown: NgbDropdown;
ngAfterViewInit() {
this.dropdown.focusFirst();
}
}