1

I have an input field that adds class active when modalOpen = true, and this works fine.

However, i want it to focus on the input field when this modal shows?

 <div [class.active]="modalOpen">
     <input>
 </div>
B Hull
  • 3,153
  • 6
  • 22
  • 24

3 Answers3

5

Add a local template variable to your input element: <input #input1>, and get a reference to it using @ViewChild('input1') input1ElementRef;.

Then, wherever you are setting modalOpen to true, also set focus on the input element with this._renderer.invokeElementMethod(this.input1ElementRef.nativeElement, 'focus', []).
Using Renderer is web worker safe.

import {Component, ViewChild, Renderer} from 'angular2/core';

@Component({
  selector: 'my-comp',
  template: `<div [class.active]="modalOpen">
       <input #input1>
     </div>
     <button (click)="showModal()">show modal</button>`
})
export class MyComponent {
  @ViewChild('input1') input1ElementRef;
  modalOpen = false;
  constructor(private _renderer:Renderer) {}
  showModal() {
    this.modalOpen = true;
    // give Angular a chance to create or show the modal
    setTimeout( _ => 
      this._renderer.invokeElementMethod(
        this.input1ElementRef.nativeElement, 'focus', []);
    );
  }
}

@Component({
  selector: 'my-app',
  template: `<my-comp></my-comp>`,
  directives: [MyComponent]
})
export class AppComponent {
  constructor() { console.clear(); }
}

plunker

Mark Rajcok
  • 362,217
  • 114
  • 495
  • 492
1

I have a sample component where I set focus when an element comes "active". Here is my approach:

export class Spreadsheet implements AfterViewChecked{

    ngAfterViewChecked(){
        //some logic to find "active" element 
        let cell = document.getElementById(this.model.current.rowIndex + '-' + this.model.current.columnIndex);
        cell.focus();
    }
}

More here: http://www.syntaxsuccess.com/viewarticle/virtualized-spreadsheet-component-in-angular-2.0

http://www.syntaxsuccess.com/angular-2-samples/#/demo/spreadsheet

TGH
  • 38,769
  • 12
  • 102
  • 135
0
<input type="text" #myInput />
{{ myInput.focus() }}

Just add {{ myInput.focus() }} right after input inside template

Sergey Gurin
  • 1,537
  • 15
  • 14