我正在使用 Angular 5 开发前端应用程序,我需要隐藏一个搜索框,但单击按钮时,应该显示搜索框并聚焦。
我尝试了在 StackOverflow 上找到的一些带有指令等的方法,但无法成功。
这里是示例代码:
@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello</h2>
</div>
<button (click) ="showSearch()">Show Search</button>
<p></p>
<form>
<div >
<input *ngIf="show" #search type="text" />
</div>
</form>
`,
})
export class App implements AfterViewInit {
@ViewChild('search') searchElement: ElementRef;
show: false;
name:string;
constructor() {
}
showSearch(){
this.show = !this.show;
this.searchElement.nativeElement.focus();
alert("focus");
}
ngAfterViewInit() {
this.firstNameElement.nativeElement.focus();
}
搜索框未设置为焦点。
我怎样才能做到这一点?
最佳答案
编辑 2022 年:
通过@Cichy 的回答阅读更现代的方式 below
像这样修改显示搜索方法
showSearch(){
this.show = !this.show;
setTimeout(()=>{ // this will make the execution after the above boolean has changed
this.searchElement.nativeElement.focus();
},0);
}
关于angular - 将焦点设置在 <input> 元素上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59719182/