Encountering the following issue: Unhandled Promise Rejection - TypeError: Unable to access property 'value' of null after implementing ngAfterViewInit in the code

I'm attempting to display a Google Map using the place_id extracted from an HTML value.

activity-details.page.html

                    <ion-col>
                        <div id="map"></div>
                        <div *ngIf="activities">
                        <input type="hidden" id="place_id" value="{{ activities.place_id }}" />
                        </div>
                    </ion-col>
                </ion-row>

This snippet represents the code displayed in the browser.

<input _ngcontent-irr-c150="" type="hidden" id="place_id" value="ChIJ21P2rgUrTI8Ris1fYjy3Ms4">

I'm striving to configure the map options as the final step after all the code is loaded.

activity-details.page.ts

    ngAfterViewInit() {
    this.geocodePlaceId(
      this.geocoder = new google.maps.Geocoder(),
      this.map = new google.maps.Map(
        document.getElementById("map") as HTMLElement,
        {
          zoom: 8,
        }
      ),
      this.infowindow = new google.maps.InfoWindow());
  }

The problem arises when I try to retrieve the place_id value from the HTML in this last function.

activity-details.page.ts

geocodePlaceId(
    geocoder: google.maps.Geocoder,
    map: google.maps.Map,
    infowindow: google.maps.InfoWindow
  ) {
    const placeId = (document.getElementById("place_id") as HTMLInputElement).value;
    geocoder.geocode({ placeId: placeId }, (results, status) => {
      ...//the remaining map setup options
  }

I keep encountering the ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'value' of null TypeError: Cannot read property 'value' of null

What could be the issue with my implementation?

Answer №1

To avoid errors, ensure an if condition is added

geocodePlaceId(
    geocoder: google.maps.Geocoder,
    map: google.maps.Map,
    infowindow: google.maps.InfoWindow
  ) {
    const placeId = (document.getElementById("place_id") as HTMLInputElement).value;
    if (placeId) {
        geocoder.geocode({ placeId: placeId }, (results, status) => {
            ...//additional map options set up
        }
    }

   // It is important to wait for a value to be assigned to placeId before setting it in the geocoder.geocode line to avoid issues.

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

Considering the move from AngularJS 1.4 to Angular 8 is a significant one, the question arises: should one opt to migrate to 1.5 before upgrading

After conducting extensive research, I am still unsure of the best approach for migrating a large, poorly structured program to Angular 8 (or at least Angular 7). The options of vertical slicing, horizontal slicing, or a complete rewrite all seem dauntin ...

Utilizing interface in NestJS for validating incoming request parameters

My goal is to utilize the interface provided by class-validator in order to validate a specific field in the incoming request body. Here's the interface structure: export enum Fields { Full_Stack_Dev = 'full stack dev', Frontend_Dev = &a ...

How to format numbers in Angular without a leading zero using the decimal pipe?

Is it possible to format decimal numbers in Angular without displaying a leading zero? I want to display statistics such as baseball batting averages in the format of .xxx instead of 0.xxx. The exception is when the average is equal to or greater than 1.0 ...

Whenever you run the ng (Angular) command, it automatically opens up a text editor for you

Following a long break in my web development project using WSL2 (VS code), I decided to update all the tools with *npm i -g npm-check-updates, ncu -u, npm install* After updating, I found that I had version @angular/core@"~15.0.4. However, this versi ...

Exploring VSCode Debugger with Typescript: Traversing through Step Over/Into leads to JavaScript file路径

Just starting out with VSCode and using it to debug node.js code written in Typescript. One thing that's been bothering me is that when I stop at a breakpoint and try to "Step Over" or "Step Into", the debugger takes me to the compiled Javascript file ...

Contrast between employing typeof for a type parameter in a generic function and not using it

Can you explain the difference between using InstanceType<typeof UserManager> and InstanceType<UserManager> I'm trying to understand TypeScript better. I noticed in TS' typeof documentation that SomeGeneric<typeof UserManager> ...

Unable to Trigger Click Event on Div Element in Angular 9

Take a look at my HTML code snippet <mat-grid-list cols="3" rowHeight="150px"> <mat-grid-tile *ngFor="let tile of tiles;index as j;" [colspan]="tile.cols" [rowspan]="tile.rows" ...

An easy way to insert a horizontal line between your text

Currently, I have two text responses from my backend and I'm considering how to format them as shown in the design below. Is it possible to automatically add a horizontal line to separate the texts if there are two or more broadcasts instead of displa ...

Building an Angular CLI application with Typescript that handles multiple HTTP calls using polling through a timer

I am working with a Django backend and I need to check the status of multiple Celery Tasks () every 3 seconds. For instance, let's say I have 4 task IDs: 3099023 3493494 4309349 5498458 My goal is to make an http.get<...>(backend) call every ...

The concept of window.trustedtypes is not defined within the Firefox browser

My application has successfully integrated trusted types. It is functioning well in Chrome, however, I am encountering an error in Firefox where it says "window.trustedtypes is undefined". Can anyone provide guidance on how to address this issue? ...

Revising a conceivably intricate template

Let's talk about managing suppliers' documents, which include code, names, and various other fields. I currently have a component export class SuppliersDetails extends MeteorComponent { supplier: any; invalidKeys: Object; // array <key&g ...

Implementing Angular Universal on an Apache Web Server

I've been facing an issue with deploying Angular ssr on Apache. It seems like configuring the apache server along with the .htaccess file is necessary. I've checked out a few links, but either I couldn't configure it properly or the instruct ...

JavaScript module declarations in TypeScript

Recently, I delved into the world of a Node library known as bpmn-js (npmjs.com). This library is coded in JavaScript and I wanted to incorporate typings, which led me to explore d.ts files. My folder structure looks like this webapp @types bpmn ...

Changing a JSON string into an object and linking it to an HTML select element in Angular 2

I have received a response from my service that I want to bind to an HTML select dropdown. However, the response appears to be in string format rather than an array. "{"Codes":{ "CountryCodes": [ { "Code": "002", "Desc": "AFGHANISTAN" ...

Issue encountered with Ionic and ssh2: process.binding is not supported

I am currently delving into the world of Ionic and experimenting with creating a basic application that utilizes SSH2 to establish an ssh connection between the app and a server. Here is a breakdown of the steps I took to encounter the issue: Steps to Rep ...

A new interface property type that is customized based on the type property that is passed in

My dilemma lies in a generic interface with a field depending on the passed type. I'm exploring the possibility of having another field that can accept any type from the passed type. For instance: interface sampleObject { name: fullName age: n ...

Explore lengthy content within Angular 2 programming

I have a lengthy document consisting of 40000 words that I want to showcase in a visually appealing way, similar to HTML. I aim to include headers, paragraphs, and bold formatting for better readability. Currently, I am developing an Angular application. D ...

type Y does not contain property X

When I encounter this error message: The property 'module' is missing in the type 'Menu'. The property 'parentId' is not found in the type 'Menu'. the code snippet triggering it appears like this: private menus: ...

Tips for developing a personalized form validator for validating JSON data exclusively in Angular

Within my Angular application, there exists a reactive form that has a single control known as configJson, which is visually represented by a <textarea> element in the DOM. The primary goal is to validate this specific form control to ensure that it ...

Can I run Angular, Flask, and MongoDB all with just the `npm start` command?

Our team is in the process of developing a web service that utilizes Angular for the front-end, Flask for the back-end server, and MongoDB as the database. When it comes time to launch our web service, we need to run three separate processes: npm start ( ...