In my TS file, I am aiming to retrieve an element using ViewChild in Angular version 15

Every time I attempt to log a ViewChild element in either the ngAfterViewInit() or ngOnInit() functions, it always logs undefined in the console.

This is how my HTML file looks:

<input type="number" #phoneNumber>

And here is my TypeScript file:

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

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

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

I have tried all possible ways to access the element using ViewChild, but nothing seems to work. How can I properly reference my input using the ViewChild decorator?

Answer №1

When using ViewChild, keep in mind that it will not provide a reference to an element that is conditionally rendered until the condition evaluates to true.</p>
<p>To work around this issue, you can define a setter for the ViewChild property, as demonstrated in <a href="https://stackoverflow.com/a/47519683/9917250">this</a> solution:</p>
<pre class="lang-js"><code> @ViewChild('phoneNumber') set phoneNumber(
    elementRef: ElementRef<HTMLInputElement> | undefined
  ) {
    console.log(elementRef);
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Obtain the local time zone based on a specified location

My current implementation involves using Luxon and the following code snippet: this.now = DateTime.local(); But now I have a requirement to retrieve the current time from a different timezone, say 'Europe/London'. Can Luxon handle this function ...

Angular6 does not recognize the property 'modal' on type 'JQuery'

Encountered an issue when trying to use jQuery in TypeScript Angular6. Seeking assistance with the following error: jQuery('#assignsp').modal('show'); Here are the steps that have been followed: 3 Steps: 1. Install jQuery. (skip if ...

modal componentProps not being updated with property

Utilizing a modal in Ionic with componentProps: //Main component someList:number[] = [1, 2]; someString:string = "test"; async presentModal(ev: any) { const modal = await this.modalController.create ...

When attempting to upload a file using .NetCore and Angular on S3, the calculated request signature does not align with the signature provided. Please verify your key and try again

I am seeking a solution to upload an image on S3 using .NetCore and Angular. My goal is to create a signed URL with the key and secret key in the backend, and then utilize this generated URL in Angular to upload the file. This is my backend code written i ...

Encountering a deadly mistake with LNK1181 while attempting to npm install web3

On my Windows system, I attempted to install the web3 node package using npm install. I followed the necessary steps by first installing Windows build tools: npm install --global --production windows-build-tools This command executed without issues, but ...

What limitations do we face when trying to change the objects received by a component through @input() in Angular?

Recently, I made the leap from angular 7 to angular 11 in my app. Everything was running smoothly until I decided to incorporate angular universal for server-side rendering. Shortly after implementing server-side rendering, a flurry of errors cropped up, ...

Using *ngFor in Angular for Parent-Child component interaction

Is there a way to iterate through a child component multiple times with different data each time? For instance, in my 'sitelist' component (parent), I aim to loop through my 'summary' component (child) as many times as needed based on ...

What is the best way to conduct tests on this React component using Jest?

I'm currently working on increasing the test coverage for a wrapper component in my codebase using jest. Although I haven't been able to identify any specific usage of this component, it's important to ensure that it is covered by tests. M ...

Ways to retrieve the value of a variable beyond its scope while using snapshot.foreach

I am experiencing an issue where the return statement returns a null value outside the foreach loop of the variable. I understand that the foreach loop creates its own scope, but I need to figure out how to return the value properly... this.selectedUserMe ...

Angular's `await` feature does not wait for the function to complete its execution

Trying to call an async function from a Cordova plugin, but the await keyword doesn't seem to be working: export class MationLiteService implements IgatewayService { async getGroupAllInfo(gatewayId: string, account: string, decryptedpasswd: string) ...

Interfaces defined as function expressions in Typescript are not recognized when written as tuples

Trying to execute a function expression in this format: export default interface IUserManager { deleteUser: ((userId: string) => Promise<void>) | ((userName: string, userSurname: string, city: string) => Promise<void>) } from within ...

Error: NullInjector - The injector encountered an error when trying to inject the Component into the MatDialogRef in the AppModule

When utilizing a component via routing as well as injecting it as the "target" of a modal dialog, I encountered an issue: export class Component1 implements OnInit { constructor(private service: <someService>, public dialogRef: MatDialogRef<Compo ...

"Troubleshooting the issue of Angular's select binding causing a disruption

The Angular version being used is 1.4.7. Within the model in question, there are two objects: 'systems', which is an array, and 'selectedSystem'. The desired outcome is for 'selectedSystem' to reference one of the objects wit ...

Exclusive Vue3 Props that cannot be used together

How can a component be created that accepts either json with jsonParserRules or jsonUrl with jsonParserRulesUrl, but not both? It would be ideal if the IDE could provide a warning when both props are specified. Example of an Attempt that does not Work < ...

"Develop a unique Angular 12 custom pipe that retrieves data through a service and converts it into a string instead of

Hello Everyone, I've encountered a problem that I need help with. import { Pipe, PipeTransform } from '@angular/core'; import { PrintingTypesService } from 'src/app/settings/services/printing-types/printing-types.service'; import { ...

Tips on how to eliminate focus after choosing a radio button in Angular Material?

This is a snippet from my HTML template file, which includes two Angular Material radio buttons. My goal is to disable the focus on the rings quickly after selecting any radio button. <div id="login-form" class="vh-100 overflow-auto" ...

React Hook Form is flagging missing dependencies in the useEffect function

Before posting this question, I made an effort to search for a solution on Google. However, I am puzzled by the warning that the linter is giving me regarding my code. The warning message reads: ./components/blocks/Contact.tsx 119:6 Warning: React Hook us ...

Combine multiple objects to create a new object that represents the intersection of all properties

Imagine you have these three objects: const obj = { name: 'bob', }; const obj2 = { foo: 'bar', }; const obj3 = { fizz: 'buzz', }; A simple merge function has been written to combine these three objects into one: ...

What is the best way to access a value from a settings.json file in an Angular .ts file?

I am working on implementing debounceTime to allow the user to finish typing before suggestions are generated. I want to give the user the ability to customize how much time is given before suggestions appear. To achieve this, I have added a configuration ...

The menu functionality is not responding when I try to access it by tapping on the screen using Ionic

After logging in, my single screen contains a home menu with four tabs: home, about, location, more. The menu functions properly in this setup. To navigate to the home page with all tabs and the menu after login, I use the following code: this.navCtrl.push ...