Angular 12: An issue has occurred due to a TypeError where properties of undefined cannot be read, specifically pertaining to the element's 'nativeElement

Within my phone number input field, I have integrated a prefixes dropdown. Below is the code snippet for this feature.

HTML code in modal

<div
  class="phone"
  [ngClass]="{ 'error_border': submitted && f.phoneNumber.errors }"
>
  <div class="phone__select">
                <span class="phone__prefix" (click)="openPrefixes()"
                >{{ selectedPrefix }}</span
                >
    <ul #prefixes class="prefixes">
      <li
        *ngFor="let prefix of availablePrefixes"
        class="prefix"
        (click)="prefixChange(prefix)"
      >
        {{ prefix }}
      </li>
    </ul>
  </div>
  <input
    class="phone__input form-control"
    maxlength="13"
    type="text"
    pattern="^(?!0+$)\d{10,}$"
    formControlName="phoneNumber"
  />
</div>

TS

 @ViewChild("prefixes") prefixes!: ElementRef;
  selectedPrefix = "+43";
  availablePrefixes = ["+43", "+49"];
  
  prefixChange(prefix: string): void {
    this.selectedPrefix = prefix;
    this.closePrefixes();
  }

  openPrefixes(): void {
    this.renderer.addClass(this.prefixes.nativeElement, "active");
  }

  closePrefixes(): void {
    this.renderer.removeClass(this.prefixes.nativeElement, "active");
  }

The code displayed above functions correctly on the page but throws an error

ERROR TypeError: Cannot read properties of undefined (reading 'nativeElement')
when implemented within a modal.

Upon opening the modal, the prefix dropdown fails to work and displays the aforementioned error message.

Is there a way to resolve this error? Are there alternative methods to achieve the same result (e.g. utilizing ngModal) ?

Your assistance and guidance would be greatly appreciated.

Answer №1

The reason for this issue is that the DOM is not fully loaded when the openPrefixes() and closePrefixes() functions are called. To solve this problem, you can use AfterViewInit to ensure that the code runs only after the view has been initialized.

ngAfterViewInit() {
     this.renderer.addClass(this.prefixes.nativeElement, "active");
  }

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

Tips for Utilizing jQuery each Loop

I am attempting to create a foreach loop that will iterate through hidden values on the page, compare them with an external API using Ajax, and display the API results in a < ul > for example. Sample model ITEM1 metavalue (which needs to be che ...

Avoid unnecessary re-rendering of React Native components with each update of the state

I need my component to display either A or B based on the user's proximity to a specific location. I developed a custom hook to determine if the user is nearby. However, I'm facing an issue where the hook constantly returns a new value of true, ...

Adding data to a defaultContent JSON column in JQuery DataTable using JavaScript

I am working with a dynamic jQuery data table. The final column in my table allows users to delete rows, but I am having trouble passing the itemId value to the specified function within the button's onClick attribute. Here is the code I have tried s ...

Using jQuery to switch between displaying full text and truncated text

How can I toggle the hidden text that appears after using the .slice function to remove the first 100 characters? This is the code snippet I am currently working with: .html <div class="col-sm-12"> <p class="pdp-product-description">Th ...

Adjust the height of the Iframe to match the content within it

After conducting my research, I have not been able to find a solution. Although I am not an expert in jQuery, it seems that the code is not functioning properly. Within the iframe are links that expand when clicked to display content. However, the height o ...

Utilizing the jQuery index for organizing JSON keys

Recently, I came across an interesting issue with a jQuery event handler in my code. When clicked, this specific event creates a JavaScript object based on a list of favorite links: $('#saveFavorites').on('click', function(){ a ...

Is there a way to adjust the dimensions of Google charts within a Bootstrap tab for a more customized appearance?

I've been working on a page that features tab navigation using Twitter Bootstrap and I want to include Google charts within each tab's content. However, I've encountered an issue where the charts are appearing in different sizes despite spec ...

TypeScript is still throwing an error even after verifying with the hasOwnProperty

There exists a type similar to the following: export type PathType = | LivingstoneSouthernWhiteFacedOwl | ArakGroundhog | HubsCampaigns | HubsCampaignsItemID | HubsAlgos | HubsAlgosItemID | TartuGecko | HammerfestPonies | TrapaniSnowLeop ...

Error: Attempting to access property 'propeller' of an undefined object has caused a TypeError

I am working on a tutorial that can be found at this link: https://tympanus.net/codrops/2016/04/26/the-aviator-animating-basic-3d-scene-threejs/ During the process, I encountered an error message: Uncaught TypeError: Cannot read property 'propeller& ...

sending information back to a middleware using a resolved promise

As a newcomer to nodejs, I am facing an issue with retrieving data from a function that returns a promise. The response from the middleware needs to be sent back to the front end. Below is the relevant code snippet: // Middleware app.get('/player&apo ...

The issue with the dark/light theming in an input arises when the autocomplete attribute is set to "on"

Seeking advice on applying a light/dark theme to an input field. I have created the input tag in Angular and styled it using Bootstrap for my application. HTML <form [formGroup]="exportDialogueForm"> <div class="form-floating mb- ...

Efficient management of pre-built assets in Vite

I am currently developing a Vue application using Vite. Within the content folder, I have numerous files (ranging from 10 to 100) located as follows: content/block/paragraph.json content/block/theorem.json content/inliner/link.json ... My goal is to creat ...

Error encountered with the root reducer due to data type mismatch

Within my Redux store setup, I have a persistedReducer initialized to include the redux-persist config and the "rootReducer": client/src/redux/store.ts: import { configureStore } from '@reduxjs/toolkit'; import { persistStore, persistReducer } f ...

What is the best way to implement a Navbar link in React.js?

I am currently working on developing a website using Reactjs. I have successfully created a Navbar with two links - Home and Contact. However, when I click on the Contact link, although the URL changes accordingly, the page itself does not update. I have s ...

What is the best way to modify the state of an array of objects by applying a filter in Vue 3?

I am currently facing an issue with a component that is listening for an emit and then attempting to filter out a user with a specific userId from the users state. The challenge lies in the fact that assigning filteredUsers to users does not appear to be ...

Each time the Angular Service is called, it undergoes a reset process

For my Angular web project, I have implemented an AuthenticationGuard and an AuthenticationService to manage security. These components are from a separate branch of the project that is functioning perfectly. This is how the process should occur: Go to ...

Searching for li elements that contain text values - a guide

I have a list of letters and I want to filter out any values that contain the text entered by the user in a textbox. Here is the design: Search List: <input type="text" id="txtSearch" /> <ul> <li>Coffee1</li> <li>Coffe ...

Trouble with mouseout listener in Wordpress causing Google Map to malfunction

Having trouble integrating a map into my WordPress site using the Google Maps API v3. The issue I am facing is that the listener assigned to the mouseout event is not functioning properly. I have copied and pasted the code from another website where it was ...

What could be the reason for ngOnChanges lifecycle hook not getting invoked?

I am currently experimenting with Angular 2 in an effort to learn more about it. I noticed that ngOnChanges is not triggering in the code below: app.component.ts: import { Component, Input } from "@angular/core" import { FormsModule } from '@angular ...

Updating the user interface in react-apollo following a delete mutation

After successfully executing a delete mutation in my React Apollo component, the UI of my app did not update as expected. Here is the code snippet for reference: const deleteRoom = async (roomId, client = apolloClient) => { const user = await getUser ...