[Fixed] Angular2 – Focus on input after modal load

Issue

I built a component in Angular 2, and I’m trying to set the focus on the specific input after a modal is loaded.

Here is what I’ve done so far:

@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');
        }
    });
}

And my input is:

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

And it’s not working 🙁

Solution

you can’t trigger any function until unless DOM rendered , wait till the your modal rendered and then trigger focus , if your using Jquery , then use jquery focus function..

so now you component look like this

@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');
        }
    });
}

and your HTML look like this

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

Leave a Reply

(*) Required, Your email will not be published