繁体   English   中英

Angular2 - 专注于模态加载后的输入

[英]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/>

这可以通过使用cdkTrapFocuscdkFocusInitial来指定哪个元素将具有初始焦点来完成 例如:

在输入元素中添加 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM