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.

2
  • post your html also Commented Aug 8, 2019 at 9:29
  • your variable is this.input, NOT this.usernameField, the function is focus() NOT focusIn() Commented Aug 8, 2019 at 10:01

3 Answers 3

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();
}
Sign up to request clarification or add additional context in comments.

5 Comments

Html code :<input #usernameField type="password" id="password" name="Password" class="form-control" placeholder="Password" [(ngModel)]="Password" #loginpassword="ngModel" [ngClass]="{'is-invalid':loginpassword.errors && loginpassword.touched}" required minlength="5">
sometime I use his trick I like to share check 👉 stackblitz.com/edit/angular-viewchild-static 😅😅
@malbarmawi Frankly speaking, I don't like setTimeout hack :(, we can't trust on it. So I avoid to use it unless it is very necessary :P
aggred 😅👍 the new version angular 8 has already fixed this trick by static property
but in all cases timeout function will run after ngAfterViewInit 😃😃
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 🧙‍♂️🧙‍♂️

Comments

0

Just inject ElementRef in constructor.

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

2 Comments

We can't give focus in constructor.... Because view is not available during constructor execution
yes. please add same line of code into ngAfterViewInit()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.