Angular 2/4 focus on input element

How to set focus on event input (click)? I have this function in place, but I obviously missed something (angular newbie here)

sTbState: string = 'invisible';
private element: ElementRef;
toggleSt() {
  this.sTbState = (this.sTbState === 'invisible' ? 'visible' : 'invisible');
  if (this.sTbState === 'visible') {
    (this.element.nativeElement).find('#mobileSearch').focus();
  }
}
+6
source share
2 answers

You can use a decorator for this @ViewChild. The documentation is at https://angular.io/api/core/ViewChild .

Here plnkr works: http://plnkr.co/edit/KvUmkuVBVbtL1AxFvU3F

This code essence boils down to giving your input element a name and attaching the click event in your template.

 <input #myInput />
 <button (click)="focusInput()">Click</button>

@ViewChild @ViewChildren (), .

export class App implements AfterViewInit {
  @ViewChild("myInput") inputEl: ElementRef;

  focusInput() {
    this.inputEl.nativeElement.focus()
  }

, . ElementRef ,  , XSS (https://angular.io/api/core/ElementRef), .

, inputEl , ngAfterViewInit.

+5

:

HTML:

<button type="button" (click)="toggleSt($event, toFocus)">Focus</button>

<!-- Input to focus -->
<input #toFocus> 

ts:

sTbState: string = 'invisible';

toggleSt(e, el) {
  this.sTbState = (this.sTbState === 'invisible' ? 'visible' : 'invisible');
  if (this.sTbState === 'visible') {
    el.focus();
  }
}
+1

All Articles