angulartypescriptviewchildangular15

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:

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