[英]Angular2 - Focus on input after modal load
I built a component in Angular 2, and I'm trying to set the focus on the specific input after a modal is loaded.我在 Angular 2 中构建了一个组件,并尝试在加载模态后将焦点设置在特定输入上。
Here is what I've done so far:这是我到目前为止所做的:
@Component({
selector: 'login',
templateUrl: './login.component.html'
})
export class LoginComponent {
showModal: boolean = false;
@ViewChild('username1') el: ElementRef;
constructor(private elementRef: ElementRef, private modalService: ModalService {
this.modalService.LoginModal.subscribe((show) => {
this.showModal = show;
if (show) {
$('#modal_login_root').modal();
this.el.nativeElement.focus();
}
else {
$('#modal_login_root').modal('hide');
}
});
}
And my input is:我的输入是:
<input #username1 type="email" class="form-control email active" name="username"
placeholder="{{ 'Login_EmailField' | translate }}" [(ngModel)]="username" />
And it's not working :(它不起作用:(
you can't trigger any function until unless DOM rendered , wait till the your modal rendered and then trigger focus , if your using Jquery , then use jquery focus function..除非DOM呈现,否则您无法触发任何功能,等到您的模态呈现然后触发焦点,如果您使用Jquery,则使用jquery焦点功能..
so now you component look like this所以现在你的组件看起来像这样
@Component({
selector: 'login',
templateUrl: './login.component.html'
})
export class LoginComponent {
showModal: boolean = false;
constructor(private elementRef: ElementRef, private modalService: ModalService {
this.modalService.LoginModal.subscribe((show) => {
this.showModal = show;
if (show) {
$('#modal_login_root').modal();
setTimeout(function(){
$('#username').focus();
},1000)
}
else {
$('#modal_login_root').modal('hide');
}
});
}
and your HTML look like this你的 HTML 看起来像这样
<input #username1 type="email" id="username"
class="form-control email active" name="username"
placeholder="{{ 'Login_EmailField' | translate }}" [(ngModel)]="username" />
只需使用输入字段添加自动对焦
<input type="text" autofocus/>
It can be done by using cdkTrapFocus and cdkFocusInitial to specify which element will have initial focus .这可以通过使用cdkTrapFocus和cdkFocusInitial来指定哪个元素将具有初始焦点来完成。 for example:
例如:
In input element add cdkFocusInitial :在输入元素中添加 cdkFocusInitial :
<input
matInput
type="text"
name="username"
[(ngModel)]="username"
cdkFocusInitial
/>
In container element add cdkTrapFocus, for example if div is the container element:在容器元素中添加 cdkTrapFocus,例如如果 div 是容器元素:
<div class="login-container" cdkTrapFocus>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.