3

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

Maximilian Riegler
  • 22,720
  • 4
  • 62
  • 71
angel
  • 171
  • 2
  • 4
  • 12

2 Answers2

1

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>
null canvas
  • 10,201
  • 2
  • 15
  • 18
1

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();
  }
Machavity
  • 30,841
  • 27
  • 92
  • 100
Prashobh
  • 9,216
  • 15
  • 61
  • 91