0

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 :(

Or Assayag
  • 5,662
  • 13
  • 57
  • 93

3 Answers3

1

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" />
Vasim Hayat
  • 909
  • 11
  • 16
0

Just add auto focus with input field

<input type="text" autofocus/>
jaseelmp
  • 357
  • 2
  • 5
0

It can be done by using cdkTrapFocus and cdkFocusInitial to specify which element will have initial focus. for example:

In input element add cdkFocusInitial:

    <input
          matInput
          type="text"
          name="username"
          [(ngModel)]="username"
          cdkFocusInitial
    />

In container element add cdkTrapFocus, for example if div is the container element:

     <div class="login-container" cdkTrapFocus>
H S W
  • 6,310
  • 4
  • 25
  • 36