Issue
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);
}
Answered By - Ali Nauman
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.