raju
raju

Reputation: 6936

How to set focus on Input Angular2 Form

I have an Input in angular2/Ionic2 form

<input #input1 autofocus type="text" [ngModel]='searchString' name='searchText' required minlength="3" (ngModelChange)="onInputChange($event)">

I want to set focus on it when page/route change.

nativeElement.focus() is not working as @ViewChild(#input1) gives angular2 element not native html element.

Upvotes: 0

Views: 899

Answers (1)

Luca Taccagni
Luca Taccagni

Reputation: 1059

what is 'autofocus' for? is not necessary

@ViewChild ('input1') el: ElementRef; // the # is used in html only

....

async ngOnInit() {
  setTimeout(() => {
    this.el.nativeElement.focus(); // with ElementRef should work, but if you encounter any problem just use 'any' type
  }, 1000);
}

Upvotes: 1

Related Questions