Encountering an error in Angular where the property 'nativeElement' is undefined when using @ViewChild

I have a div in my code named #map that will be displayed after a certain condition is met in a for loop.

<div *ngFor="let message of fullMessagesArr">
 <div *ngIf="message.replyMap">
   <div #gmap style="width:100px;height:400px"></div>
 </div>
</div> 

Below is my .ts file with the initMap function.

@ViewChild('gmap') gmapElement: ElementRef;
map: google.maps.Map;

  initGMap = () => {
    const mapProp = {
      center: new google.maps.LatLng(6.9404, 79.8464),
      zoom: 15,
      mapTypeId: google.maps.MapTypeId.satellite
    };
    this.map = new google.maps.Map(this.gmapElement.nativeElement, mapProp);
  }

The initGMap function is called within the sendMessage function.

Answer №1

It seems that you are attempting to access an element before it is visible in the DOM. One way to resolve this issue is to either use setTimeOut or leverage the ngAfterContentInit lifecycle hook to ensure that the DOM has finished rendering.

export class AppComponent implements OnInit, OnDestroy, AfterContentInit {

    public ngAfterContentInit(): void {
       const mapProp = {
           center: new google.maps.LatLng(6.9404, 79.8464),
           zoom: 15,
           mapTypeId: google.maps.MapTypeId.satellite
       };
       this.map = new google.maps.Map(this.gmapElement.nativeElement, mapProp);
    }
}

Alternatively, you can use setTimeOut to delay the element access.

initGMap = () => {
    const mapProp = {
      center: new google.maps.LatLng(6.9404, 79.8464),
      zoom: 15,
      mapTypeId: google.maps.MapTypeId.satellite
    };
    setTimeout(() => {
         this.map = new google.maps.Map(this.gmapElement.nativeElement, mapProp);
    }, 3000);
  }

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

Traversing through intricate weather data in JSON with AngularJS

I've been diving into learning angularJS and have hit a roadblock when it comes to extracting values from specific objects in a JSON file. Despite searching online for solutions, all I've found are basic examples that don't quite fit my curr ...

The enigma of TypeScript

Whenever I try to declare or initialize data members in a class, the following methods never seem to work: var view: string[]; var view: string[] = []; let view: string[]; let view: string[] = []; Even though the TypeScript documentation states that it s ...

What is the best way to activate an event listener only after a button has been clicked?

Currently, I am developing a game that includes a timer and an event listener that notifies the user not to switch tabs. However, I am facing an issue where the event listener triggers before the game's start button is clicked. Is there a way in JavaS ...

Exploring Typescript and Clean Architecture with an In-Memory Database/Repository

Currently, I am integrating clean architecture in my latest project and facing challenges with repositories, data sources, and terminology. My aim is to test my useCases using an in-memory repository as I am only concerned about the business logic at this ...

What techniques can I use to streamline the following?

var cleanWord = word .split(/[^a-z0-9\s.\|]/gi) .join("") .replace(/([~@#$%^&*()_+=`{}\[\]\\:;<>\/ ])+/g, ""); I suspect that I am redundantly using the join function twice here. Is there a way to ...

Embedding a YouTube video in a view player using HTML5

So I've got a question: can you actually open a youtube video using an HTML5 video player? I'm looking for a more mobile-friendly way to watch youtube videos, and my idea was to upload a thumbnail image and then set up an onclick function to disp ...

Error Message for Sequelize Validation Fails to Appear as Expected

I am trying to implement Sequelize model validation in order to validate a form field. When the book or author fields are left empty, I want this message to be displayed: Oops! An error occurred. "Title" is required. "Author" is required. The issue I&ap ...

When working with express.js, the following error may occur: Uncaught Error [ERR_HTTP_HEADERS_SENT]: Unable to modify headers after they have been sent to the client

Seeking assistance for resolving this issue. The purpose of this code is: Update the artist using the specified artist ID and data from the request body, then save it to the database. Return a 200 response with the updated artist in the response body. If ...

Nodejs and express authentication feature enables users to securely access their accounts by verifying their identity before they

I am currently working on a straightforward registration page that needs to save user input (name, email, password) into a database. My tools for this task are express and node. What I am experimenting with is consolidating all the database operations (suc ...

What is the best way to share both text and an image URL in a single tweet through the Twitter API

Currently, I am utilizing the Twitter API Client for node which includes both the REST and Streaming API. You can find more information about this client by visiting this link. Specifically, I am working with the twit API in conjunction with nodejs. My go ...

What is preventing me from loading js and css files on my web pages?

I have developed a web application using SpringMVC with Thymeleaf and I am encountering an issue while trying to load javascript and CSS on my HTML5 pages. Here is a snippet from my login.html: <html xmlns="http://www.w3.org/1999/xhtml"> <head&g ...

Struggling to construct a project using parcel, continually encountering issues with unsupported file types

My attempt at creating a project using parcel has hit a snag. Despite diligently following the guidelines provided in my assignment, an error message consistently appears in my terminal each time I initiate the command: parcel src/index.html The error mes ...

Are you searching for the origin of a dynamic dropdown widget or database?

Currently, I am browsing through and I have a query regarding accessing all available classes/options for the courses in a semester. There is a class locator on the top left of the page with a dynamic drop-down menu. Can anyone suggest how I can access ...

Issue: Kindly update your dependencies to the latest version of core-js@3

When trying to execute npm start, I encountered an error stating "An unhandled exception occurred: Could not find module "@angular-devkit/build-angular". I attempted to resolve this by installing it using npm install @angular-devkit/build-angular, but the ...

What is the most effective way to obtain a customer's latitude and location by prompting them to drop a pin on Google Maps?

My Android app has an API, but on my website I'm wondering how I can retrieve a person's location by having them place a marker on a Google Map. Is there a standard method for this? I need to obtain the latitude and longitude coordinates and send ...

Utilizing Angular 1.5 and ES6 to Enhance Dependency Injection

Hi there, I am currently exploring Angular and attempting to integrate ES6 into my workflow. I seem to be facing an issue with dependency injection where I cannot seem to get it working as expected. Here is a snippet from my index.js file: import ...

Angular ngClass and ngIf directives failing to update upon alterations

In my current Angular project, I am working on a functionality where I need to dynamically change a class based on a variable without having to refresh the page. I have experimented with *ngIf/else and [ngClass] directives, which do work, but unfortunatel ...

Modify the background's color and incorporate a pointlight using three.js

Recently, I have been exploring the capabilities of three.js. One interesting challenge I encountered was creating a cube within a wireframe cube. However, I found myself struggling to alter the background color in my project. I believe that incorporating ...

Is there a way to compile my Angular application using `npm run build : production` instead of the conventional `npm run build --production` command?

Greetings! My Angular application is currently being built using the following command: npm run build --production Alternatively, it can be built using the command: npm run build -- --c production However, I am interested in building my application using ...

Utilizing async await in a JavaScript event: A guide

I have coded the introduction page for my game, which includes a submit button and a textbox for users to input their username. Upon pressing the submit button, the code posts the name into a JSON file and retrieves all the data from the JSON file to sen ...