angel
angel

Reputation: 171

Angular 2 .focus() not working

I want to open a modal window and that the input that is in it be focused.

in the html file

<img id='searchIcon' 
     src="images/search.png" 
     class="icon iconCenter" 
     data-toggle="modal" 
     data-target="#myModal" 
     (click)='focusSearch();' />

<div id="myModal" class="modal fade modal-container" role="dialog">
    <h3>SEARCH</h3>
    <input id='inputSearch' type="text" autofocus>
</div>

With the autofocus attribute I got focus the first time that I open the modal view, but after I close and open the modal again doesn't do anything.(in firefox doesn't work at all)

in the ts file

focusSearch(){
    document.getElementById("inputSearch").focus();
}

If someone can leave a quick demo I would appreciate it

Upvotes: 3

Views: 13317

Answers (2)

Prashobh
Prashobh

Reputation: 9542

Set focus example

Html

   <button (click)="setFocus()">Set Focus</button>
    <input type="text" [(ngModel)]="term2" #inputBox>

Component

import { Component, ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'app-general',
  templateUrl: './general.component.html',
  styleUrls: ['./general.component.scss']
})
export class GeneralComponent {

  @ViewChild("inputBox") _el: ElementRef;

  setFocus() {
    this._el.nativeElement.focus();
  }
}

You can modify the code according to your needs. Also you can set the focus just after the component has loaded. For example

 ngAfterViewInit() {
    this._el.nativeElement.focus();
  }

Upvotes: 1

null canvas
null canvas

Reputation: 10613

Try this, without a function

<img id='searchIcon' src="images/search.png" class="icon iconCenter" data-toggle="modal" data-target="#myModal" (click)='myInput.focus()'>
    <div id="myModal" class="modal fade modal-container" role="dialog">
       <h3>SEARCH</h3>
       <input id='inputSearch' type="text" autofocus #myInput>
    </div>

Upvotes: 1

Related Questions