Angular 角度2-模态载荷后关注输入

Angular 角度2-模态载荷后关注输入,angular,Angular,我在Angular 2中构建了一个组件,我试图在加载一个模态后将焦点设置在特定的输入上 以下是我迄今为止所做的工作: @Component({ selector: 'login', templateUrl: './login.component.html' }) export class LoginComponent { showModal: boolean = false; @ViewChild('username1') el: ElementRef; constructor

我在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');
        }
    });
}
    <input #username1 type="email"  id="username"
    class="form-control email active" name="username"
         placeholder="{{ 'Login_EmailField' | translate }}" [(ngModel)]="username" />
您的HTML如下所示

@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');
        }
    });
}
    <input #username1 type="email"  id="username"
    class="form-control email active" name="username"
         placeholder="{{ 'Login_EmailField' | translate }}" [(ngModel)]="username" />

只需使用输入字段添加自动对焦

<input type="text" autofocus/>

下面是一个使用ElementRef的例子,我建议您在modals中使用ng2引导:它不起作用。它工作了一秒钟,然后焦点消失了。