【发布时间】:2020-11-29 17:51:05
【问题描述】:
<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。 Stack answer
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>
【问题讨论】:
-
试试应该有一种方法可以使其与
ngIf一起工作,而无需setTimeout。@ConnorsFan 你说得对,不需要隐藏,我会更新我的帖子你也不需要setTimeout。请参阅下面的答案。
标签: angular