[英]Angular 2+ how to get focus to modal inputs on opening the modal?
In a custom modal component that I have built, I want to get the input in the modal focused whenever the modal is opened在我构建的自定义模态组件中,我希望在模态打开时聚焦模态中的输入
I tried two approaches:我尝试了两种方法:
1) Using ViewChild
and ElementRef
, then firing the focus(method), on modal open; 1)使用
ViewChild
和ElementRef
,然后在模式打开时触发焦点(方法);
2) Using document.getElementByID('test').focus()
method; 2) 使用
document.getElementByID('test').focus()
方法;
None of them worked他们都没有工作
I tried testing another document property and it worked.我尝试测试另一个文档属性并且它有效。
document.getElementByID('test').innerHtml = 'test'
but not the focus但不是重点
simplified html for the modal:模态的简化 html:
<div [class.modal--open]="_open">
<input #codeInput type="text" id='test'>
</div?
ts: TS:
@ViewChild('codeInput') codeInput: ElementRef
@Input() set open(value: boolean) {
this._open = value;
if (value) {
// here is where i need to get focus on the input
document.getElementByID('test').focus() // did not work
this.codeInput.nativeElement.focus() // did not work
}
}
Demo for testing https://stackblitz.com/edit/angular-2ye3ag测试演示https://stackblitz.com/edit/angular-2ye3ag
Just use autofocus in the input field只需在输入字段中使用自动对焦
<input type="text" name="firstName" autofocus>
You have an error in modal class declaration, correct it and it will work您在模态类声明中有错误,更正它,它将起作用
<div [ngClass]="['modal', style]" [class.modal--open]="_open">
^
<div [ngClass]="modal" [class.modal--open]="_open">
https://stackblitz.com/edit/angular-zsszxc https://stackblitz.com/edit/angular-zsszxc
If you want to do some dynamic focusing then you can use the afterviewInit lifecycle hook where after viewInit you set the focus using renderer rather than native methods.如果你想做一些动态聚焦,那么你可以使用 afterviewInit 生命周期钩子,在 viewInit 之后你使用渲染器而不是本地方法设置焦点。
In you component在你的组件中
AfterViewinit() {
this._renderer.setAttribute(elRef,'focus',true);
}
I figured out the problem, the focus is working it just needs some time to fire, I wrapped the focus()
method with a setTimeOut()
and it worked我发现了问题,焦点正在工作,它只需要一些时间来触发,我用
setTimeOut()
包装了focus()
方法并且它起作用了
if (value) {
setTimeout(() => {
this.codeInput.nativeElement.focus()
}, 1000)
}
full solution https://stackblitz.com/edit/angular-2ye3ag完整的解决方案https://stackblitz.com/edit/angular-2ye3ag
For those using - ng-Bootstrap对于那些使用 - ng-Bootstrap
Only after calling the modal method open(...)
, you can take the element by id, and call method focus()
只有在调用模态方法
open(...)
后,才能通过 id 获取元素,并调用方法focus()
public createCustomModal(modalDivElement: any, autoFocusElement?: string)
{
let ngbModalRef = this.ngbModalService.open(modalDivElement);
if (autoFocusElement)
{
document.getElementById(autoFocusElement).focus();
}
return ngbModalRef;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.