[英]Angular2 - Focus on input after modal load
我在 Angular 2 中構建了一個組件,並嘗試在加載模態后將焦點設置在特定輸入上。
這是我到目前為止所做的:
@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');
}
});
}
我的輸入是:
<input #username1 type="email" class="form-control email active" name="username"
placeholder="{{ 'Login_EmailField' | translate }}" [(ngModel)]="username" />
它不起作用:(
除非DOM呈現,否則您無法觸發任何功能,等到您的模態呈現然后觸發焦點,如果您使用Jquery,則使用jquery焦點功能..
所以現在你的組件看起來像這樣
@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');
}
});
}
你的 HTML 看起來像這樣
<input #username1 type="email" id="username"
class="form-control email active" name="username"
placeholder="{{ 'Login_EmailField' | translate }}" [(ngModel)]="username" />
只需使用輸入字段添加自動對焦
<input type="text" autofocus/>
這可以通過使用cdkTrapFocus和cdkFocusInitial來指定哪個元素將具有初始焦點來完成。 例如:
在輸入元素中添加 cdkFocusInitial :
<input
matInput
type="text"
name="username"
[(ngModel)]="username"
cdkFocusInitial
/>
在容器元素中添加 cdkTrapFocus,例如如果 div 是容器元素:
<div class="login-container" cdkTrapFocus>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.