0

I have already imported ViewChild,ElementRef,Renderer in ts file but it's showing error of "ERROR TypeError: Cannot read property 'nativeElement' of undefined"

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

@ViewChild('usernameField') input : ElementRef;

this.usernameField.nativeElement.focusIn();

expect focus on input element.

Muhammed Albarmavi
  • 23,240
  • 8
  • 66
  • 91
Om Prakash
  • 19
  • 4

3 Answers3

1

I think this will work

Instead of

this.usernameField.nativeElement.focusIn();

try

this.usernameField.nativeElement.focus();

Or else post your html so that we can see what is wrong?

Just check your input tag #usernameField

Like

<input #usernameField

And change your ts

@ViewChild('usernameField') usernameField: ElementRef;

Also make sure you have added focus in ngAfterViewInit

Like

ngAfterViewInit() {
    this.usernameField.nativeElement.focus();
}
Kiran Shinde
  • 5,732
  • 4
  • 24
  • 41
0

the input will be set when ngAfterViewInit run mean you can't use before like in ngOnInit() method the value at that time will be undefined

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

in angular verion 8+

@ViewChild('usernameField',{static : true}) usernameField: ElementRef;

ngOnInit() {
 this.usernameField.nativeElement.focus();
}

check this How should I use the new static option for @ViewChild in Angular 8?

check this live demo ‍♂️‍♂️

Muhammed Albarmavi
  • 23,240
  • 8
  • 66
  • 91
0

Just inject ElementRef in constructor.

constructor(private el:ElementRef){ this.el.nativeElement.querySelector('input[type:"text"]').focus(); }

Sufyan Shaikh
  • 94
  • 1
  • 6