<div class="dropdownContainer" placeholder="test" (click)="ShowDropDown()" />
<div #tref *ngIf="showDropDown == 1" class="dropdownList" (focusout)="HideDropDown()" style="border:1px solid black;" >this is my test</div>
单击dropDownContainer后,我希望出现dropdownList并将焦点放在上面。
我曾尝试使用
@ViewChild("tref", {read: ElementRef}) tref: ElementRef;
方法,但它返回undefined,因为在div
单击上面的元素之前,该元素在DOM中不存在。如何自动聚焦于动态NON INPUT DOM对象?
编辑根据建议更新了我的代码,这仍然不会自动关注div。
@ViewChild("tref") tref: ElementRef;
ShowDropDown() {
this.showDropDown = 1;
this.tref.nativeElement.focus();
console.log(this.tref);
}
HideDropDown(){
console.log('test out')
this.showDropDown = 0;
}
<input #tref class="dropdownContainer" placeholder="george" (click)="ShowDropDown()" />
<div tabindex="-1" (focusout)="HideDropDown()" [hidden]="showDropDown == 0" class="dropdownList" style="border:1px solid black;" >this is my test</div>
问题的答案有两个答案。
1)DIVS除非具有tabindex,否则不能具有焦点。堆叠答案
2)我需要包括,setTimeout(() => this.tref.nativeElement.focus(), 1);
因为hidden
尚未自动准备好接收焦点的元素。
3)* ngIf和hidden都起作用,一旦我完成上述修复
清理代码
import { Component, ElementRef , ViewChild } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.less']
})
export class AppComponent {
constructor() {
}
showDropDown = 0;
@ViewChild("tref") tref: ElementRef;
ShowDropDown() {
this.showDropDown = 1;
setTimeout(() => this.tref.nativeElement.focus(), 1);
}
HideDropDown(){
this.showDropDown = 0;
}
test(){ console.log('works');}
}
<div tabindex="-2" class="dropdownContainer" placeholder="george" (click)="ShowDropDown()" ></div>
<div tabindex="-1" #tref [hidden]="showDropDown == 0" class="dropdownList" style="border:1px solid black;" (click)="test()" (focusout)="HideDropDown()">this is my test</div>
您可以在ViewChildren
和QueryList.changes
事件的帮助下,在下拉菜单元素显示后立即对其进行聚焦。无论元素在视图中花费多长时间,该技术都有效。
在模板中,为tabindex
下拉列表提供属性div
:
<div class="dropdownContainer" (click)="showDropDown = true">
Click here to show the dropdown
</div>
<div #dropDownDiv *ngIf="showDropDown" tabindex="1" class="dropdownList" (focusout)="showDropDown = false">
This is the dropdown element
</div>
在代码中,使用检索dropdown元素ViewChildren
,并在中设置QueryList.changes
事件处理程序ngAfterViewInit
。当通知您该元素已变得可见时,可以将焦点设置在该元素上:
showDropDown = false;
@ViewChildren("dropDownDiv") private dropDownDivList: QueryList<ElementRef>;
ngAfterViewInit() {
this.dropDownDivList.changes.subscribe((list: QueryList<ElementRef>) => {
if (list.length > 0) {
list.first.nativeElement.focus();
}
});
}
有关演示,请参见此堆叠闪电战。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句