Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I want to get element via ViewChild in TS file, Angular version is 15

When I try to log a ViewChild element in ngAfterViewInit() or ngOnInit() it logs undefined in the console.

HTML file:

<input type="number" #phoneNumber>

TS file:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@ViewChild('phoneNumber',{static:false}) phoneNumber: ElementRef;

ngOnInit(): void {
  console.log(this.phoneNumber);
}

ngAfterViewInit():void{
  console.log(this.phoneNumber);
}

I did every way to get element via ViewChild it won’t work. How do I get a reference to my input using the ViewChild decorator?

>Solution :

ViewChild will not return a reference for an element that is rendered conditionally until the condition becomes truthy.

In this case, you can use a setter for the ViewChild decorated property, like in this answer:

 @ViewChild('phoneNumber') set phoneNumber(
    elementRef: ElementRef<HTMLInputElement> | undefined
  ) {
    console.log(elementRef);
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading