2017-07-25 76 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