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

215 Views Asked by At

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:

@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?

1

There are 1 best solutions below

0
On BEST ANSWER

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);
  }