2017-07-25 74 views
0

我在Angular 2中构建了一个组件,并且我试图在加载模式后在之后将焦点设置在特定输入上。Angular2 - 在模态加载后专注于输入

这里是我心中已经迄今所做的:

@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" /> 

和它不工作:(

+0

这里添加自动对焦例如使用ElementRef HTTPS: //sackoverflow.com/a/40537428/924646 –

+0

我会建议使用ng2-bootstrap for your modals:https://valor-software.com/ngx-bootstrap/#/modals –

回答

0

你不能触发任何功能直到除非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" /> 
0

只是输入字段

<input type="text" autofocus/> 
+1

它的不工作。它工作一秒钟,然后焦点消失。 – OrAssayag