The Google Maps API is throwing an error because it cannot access the property 'nativeElement' of an undefined object

I'm currently using Google Maps and I want to display the map only if a certain condition is true.

HTML:

 <div *ngIf="anyboolToShowMapOrNot" #map id="map"></div>

Here's my TypeScript code:

  @ViewChild("map",{static: true}) mapElement:ElementRef;
  map: any;
  constructor(private shareService: ShareService) { }

  ngOnInit() {
  }
  ionViewWillEnter(){
    this.initMap();
  }

  initMap(){
    this.map = new google.maps.Map(this.mapElement.nativeElement,this.shareService.getMapOptions(google));
    for(let i = 0; i < 10 ; i++){
     this.addMarker(this.map,i,i,"jow sicha");
    }
  }

While the map functions properly without the ngIf, I encounter the following error when using ngIf:

Cannot read property 'nativeElement' of undefined

Answer №1

By utilizing the {static: true} in your @ViewChild, the value remains static and won't update dynamically. This can pose a challenge when using *ngIf to toggle the existence of an element.

On the other hand, when you opt for {static: false}, timing becomes crucial. Ensure that your variable is updated before accessing it to avoid potential issues.

An effective method to track the update of a @ViewChild value is to implement a getter/setter approach.

private _elementRef: ElementRef;

@ViewChild("element", {static: false}) get elementRef(): ElementRef { return this._elementRef; }
set elementRef(newValue: ElementRef) {
  if (this._elementRef !== newValue) {
    this._elementRef = newValue;
    // Perform necessary actions when a new value is set.
  }
}

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

Identifying collisions or contact between HTML elements with Angular 4

I've encountered an issue that I could use some help with. I am implementing CSS animations to move p elements horizontally inside a div at varying speeds. My goal is for them to change direction once they come into contact with each other. Any sugges ...

Tips for binding data to numerous dynamic controls

Implementing reactive forms in my Angular project allowed me to create a simple form for adding employee work hours and breaks. The challenge I encountered was the inability to bind data from break controls. In the .ts file export class AddAppointmentForm ...

Error Uncovered: Ionic 2 Singleton Service Experiencing Issues

I have developed a User class to be used as a singleton service in multiple components. Could you please review if the Injectable() declaration is correct? import { Injectable } from '@angular/core'; import {Http, Headers} from '@angular/ht ...

Navigating to an external link directing to an Angular 5 application will automatically land on

I am struggling to comprehend why a link from an external source to my Angular app keeps redirecting to the default route page when accessed from a browser. The scenario involves a user entering an email address, triggering an API that sends an email cont ...

"Encountered a 'NextAuth expression cannot be called' error

Recently, I delved into learning about authentication in Next.js using next-auth. Following the documentation diligently, I ended up with my app/api/auth/[...nextauth]/route.ts code snippet below: import NextAuth, { type NextAuthOptions } from "next-a ...

What is the best way to integrate ag-grid with Observable in Angular 2?

After conducting extensive research on the Internet, I am still struggling to connect the pieces. My angular2 application utilizes an Observable data source from HTTP and I am attempting to integrate ag-grid. However, all I see is a loading screen instead ...

Creating an auth guard in Angular Fire v7 using the latest API (not backwards compatible)

I encountered an issue Error: Unable to handle unknown Observable type when attempting to utilize v7 Angular Fire with the latest API. Specifically "@angular/fire": "^7.4.1" which corresponds to angular 14, firebase 9. Please not ...

My application is experiencing issues due to a malfunction when refreshing with query parameters in Angular 2

My URL contains query parameters, and after a successful transaction that clears those parameters, pressing the back button causes them to reappear. Additionally, if I refresh the page, an illegal action occurs - the same transaction is repeated and data ...

What is the process for defining a global variable within a module in Typescript?

I've already included a global value in my global JavaScript context: const fs = require('fs') For a specific reason, I need to include it in the global scope. Now, I want to create a .d.ts file to declare the global variable with a stron ...

Issue TS2307 encountered following the transition from Angular 11 to Angular 12 in a project migration

After upgrading my project from Angular 11 to Angular 12, I encountered errors while using the ng update command. Instead of troubleshooting further, I decided to take a more manual approach. I started by creating a brand new Angular 12 project, re-adding ...

What is the best way to end a Google OAuth session using Firebase on an Ionic 2 application?

My Ionic 2 app integrates Google Authentication using Firebase. I have implemented a logout button within the app that calls the Firebase unauth() method. However, this only disconnects the Firebase reference and does not terminate the Google OAuth session ...

Difficulty encountered when trying to apply a decorator within a permission guard

I'm a newcomer to Nestjs and I am currently working on implementing Authorization using Casl. To achieve this, I have created a custom decorator as shown below: import { SetMetadata } from '@nestjs/common'; export const Permission = (acti ...

New versions of Angular (2.0.0-beta.17) are experiencing issues with module

Have you encountered any issues with importing modules in the latest version of Angular2? I've noticed that the module names have been updated, for example angular2/core has been changed to @angular/core. Despite this change, I keep getting an error f ...

Is there a way to extract the current view date information from fullcalendar using Angular?

When working with HTML code... <full-calendar defaultView="dayGridMonth" [plugins]="calendarPlugins" #calendar></fullcalendar> I am wondering how to extract the date information from the #calendar element. I attempted to consult the fullcal ...

When trying to pull a component from Svelte, I receive an error message stating "Selection Range

I'm still relatively new to svelte, so I might be handling things incorrectly. Whenever I attempt to separate my button component, regardless of whether I name the component ./Button.svelte, ./Button, Button.svelte, or try variations with capitalizat ...

Angular 2 - Unable to access the AssetUrl property due to undefined value

Just getting started with angular2 and material-design. Attempting to integrate the two. I decided to clone this material2-app, which is built on angular2 and material2 and ran npm install. However, when I tried running npm start to start a server, I enc ...

Is it possible for a node and @angular/cli based application to function without an internet connection?

As a newcomer to the world of angular/cli and node, I am eager to build an application using Angular and deploy it to an environment where all external communication is blocked by a firewall. In this restricted setting, even accessing search engines is imp ...

Typescript disregarding conditional statements

Looking for some assistance with a Next.JS React-Typescript application Here's my code snippet for handling the video HTML element const videoRef = useRef<HTMLVideoElement>(); useEffect(() => { videoRef !== undefined ? videoRef.current. ...

I am currently unable to retrieve any results for my fullcalendar tooltip

I am currently working on setting tooltips for events using Primeng's fullcalendar. Despite initializing the tooltip in the web console, I am unable to see it when hovering over an event. My development environment includes Typescript, Primeng 7.0.5, ...

Error encountered when deploying an IONIC app to an Android device: The task 'wrapper' was not found in the main project directory 'android'

Encountering an error while deploying my ionic app to Android. Even though gradle is installed when checking cordova requirements, I am still getting a message that it seems like gradle is missing. What could possibly be causing this issue? auli@auli-H81H ...