An Unhandled Promise Error has occurred: TypeError - Unable to access the 'nativeElement' property as it is undefined

I encountered the following issue: ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'nativeElement' of undefined.

This problem arises when I attempt to include a div with an ngIf statement within a Google map:

HTML:

                <div class="form-group">
                <label>Location by map?</label>
                <mat-select formControlName="ubication" [(ngModel)]="mapVisibility" class="form-control" placeholder="Select option">
                    <mat-option disabled>Select option</mat-option>
                    <mat-option value="visible">Yes</mat-option>
                    <mat-option value="hidden">No</mat-option>
                </mat-select>
            </div>

            <div *ngIf="mapVisibility === 'visible'">
                <div class="example-form">
                    <mat-form-field class="example-full-width">
                        <input matInput type="text" (keydown.enter)="$event.preventDefault()" autocorrect="off" autocapitalize="off" spellcheck="off" #agmSearch placeholder="Enter address">
                    </mat-form-field>
                </div>

                <agm-map id="googleMap" [latitude]="lat" [longitude]="lng" [zoom]="zoom">
                    <agm-marker [latitude]="lat" [longitude]="lng" [markerDraggable]="true" (dragEnd)="markerDragEnd($event)"></agm-marker>
                </agm-map>
            </div>

TS:

mapVisibility: string;

ngOnInit() {
    this.getPlacesAutocomplete();
}

getPlacesAutocomplete() {
// load Places Autocomplete
this.mapsAPILoader.load().then(() => {
this.setCurrentLocation();
this.geoCoder = new google.maps.Geocoder;

let autocomplete = new google.maps.places.Autocomplete(this.searchElementRef.nativeElement, {
  types: ['address']
});
autocomplete.addListener('place_changed', () => {
  this.ngZone.run(() => {
  // get the place result
  let place: google.maps.places.PlaceResult = autocomplete.getPlace();

  // verify result
  if (place.geometry === undefined || place.geometry === null) {
    return;
  }

  // set latitude, longitude and zoom
  this.lat = place.geometry.location.lat();
  this.lng = place.geometry.location.lng();
  this.zoom = 12;
  });
 });
});
}

private setCurrentLocation() {
if ('geolocation' in navigator) {
  navigator.geolocation.getCurrentPosition((position) => {
    this.lat = position.coords.latitude;
    this.lng = position.coords.longitude;
    this.zoom = 15;
    this.getAddress(this.lat, this.lng);
  });
}
}

  getAddress(latitude, longitude) {
this.geoCoder = new google.maps.Geocoder();
this.geoCoder.geocode({ 'location': { lat: latitude, lng: longitude } }, (results, status) => {
  console.log(results);
  if (status === 'OK') {
    if (results[0]) {
      this.zoom = 12;
      this.address = results[0].address_components[1].long_name + ' ' + results[0].address_components[0].long_name;
    } else {
      window.alert('No results found');
    }
  } else {
    window.alert('Geocoder failed due to: ' + status);
  }
});
}

The code was sourced from: Angular 8/7 | Add Google Maps with Location Search in Angular 2 plus Applications using Angular Google Maps Module (@agm/core) Easily

ERROR: Image error

Despite encountering this issue, the map functions correctly. However, I am unable to implement location search functionality by entering an address in an input field, which works when the div containing the ngIf is removed. Any insights on this matter?

Answer №1

Replace ngOnInit with ngAfterViewInit for better functionality

ngAfterViewInit () {
    this.getPlacesAutocomplete();
}

Prioritize ngAfterViewInit over ngOnInit when dealing with view queries.

To ensure the element is available, switch from using *ngIf to hidden. This way, the searchElementRef will not be null until the condition is true.

<div [hidden]="mapVisibility === 'visible'">
 ...
</div>

Answer №2

To ensure your function is called after the Component is initialized, use ngAfterViewInit

ngAfterViewInit() {
    this.getPlacesAutocomplete();
}

Alternatively, you can wrap your code in a setTimeout function (not recommended):

ngOnInit() {

setTimeout( _ =>   this.getPlacesAutocomplete() , 1000)

}

If you opt for ngAfterViewInit, remember to include

class MyComponent implements AfterViewInit

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

Angular2's ngx-datatable features the ability to filter search results when the backspace key is

I am currently utilizing ngx-datatable in my Angular project and attempting to implement a filter functionality. Although I have successfully added the filter to the specified column, I encounter an issue when erasing filter characters using the backspace ...

Adapting setInterval Timer in Angular Using a Range Slider

Currently, I am working with Ionic 4 and Angular. In my project, I aim to incorporate the Ionic range slider. This useful feature allows users to adjust a range of values by simply moving a slider. However, I encountered an issue regarding the refresh rate ...

Implementing reCaptcha on React Native: A Step-by-Step Guide

Currently, I am in the process of integrating a reCaptcha validator into a login screen for a react-native application that needs to function seamlessly on both web and mobile platforms. Despite being relatively new to programming and lacking experience w ...

The object literal is limited to defining recognized properties, and 'clientId' is not present in the 'RatesWhereUniqueInput' type

Currently, I am using typescript alongside prisma and typegraphql in my project. However, I have encountered a type error while working with RatesWhereUniqueInput generated by prisma. This input is classified as a "CompoundUniqueInput" due to the database ...

Angular-fontawesome icons are experiencing issues with their background color not scaling properly

Currently utilizing angular-fontawesome, I am seeking to alter the background color of a font-awesome fa-icon <fa-icon class="vue-icon" [icon]="faVue" ></fa-icon> To change the color, I modified the CSS using ...

Oops! The API request was denied with error code 401 - Unauthorized in React

I have been working on incorporating an API into my front-end project using React/Typescript. The documentation for the API specifies that authorization requires a key named token with a corresponding value, which should be included in the header. To stor ...

Running the Angular application using index-dev.html instead of index.html with angular-cli

I created an Angular project using angular-cli (version 1.0.2). However, I want to run it from index-dev.html instead of index.html. Both files will have the same content, just different names. When not using angular-cli, I know how to configure lite-serv ...

Utilize various interfaces for a single object

I'm working on a Typescript project where I need to pass the same object between multiple functions with different interfaces. These are the interfaces: export interface TestModel { fileName:string, year:number, country:string } export interfac ...

What steps are needed to enable WebStorm's autocompletion for external libraries?

As a beginner user of WebStorm and TypeScript, I am currently experimenting with incorporating the libstl library into my code. The snippet below is what I have written so far: var PriorityQueue = require('libstl').PriorityQueue; var queue = ne ...

Enum-centric type guard

Could I create a custom type guard to verify if a specified string is part of a specific string enum in a more specialized way? Check out the following example: enum MyEnum { Option1 = 'option one', Option2 = 'option two', } const ...

Adding comments in TypeScript: A quick guide

Hey there, I'm new to TS and could use some help. Here is the code snippet I have: I want to comment out the logo but adding "//" and '/*' doesn't seem to work. This is what I tried: // <LogoComponent classes={{container: style.log ...

Visual Studio Code's Intellisense is capable of detecting overloaded functions in JavaScript

What is the best way to create a JavaScript overload function that can be recognized by Visual Studio Code IntelliSense, and how can this be properly documented? A good example to reference is Jasmine's it() function shown below: function it(expecta ...

In Angular, the data is displayed in the console but is not visible in the application

After successfully fetching data from the backend and seeing it displayed in the console https://i.sstatic.net/eRjli.png However, there seems to be an issue with rendering the data even though it is being recognized. Here's the relevant code snippet: ...

Cutting-edge Angular2 modules

Starting a new Sails + Angular2 project has been quite the adventure for me. I followed the module configurations from a tutorial I found, but then realized they were different from those in Google's latest heroes tutorial. After encountering some npm ...

What is the best way to send parameters through the router in Next14?

Is there a way to pass parameters through the router with NextJS 14? I'm developing an app that features multiple items, and when a user clicks on one, they should be taken to that item's individual page. I'd like the URL to display as http ...

Angular is getting hung up on the process of "reloading client(s)" and failing to properly refresh the page

As a React developer, I've decided to start learning Angular. I created a new project using "ng new my-first-app", but I'm facing an issue with hot module reload. It stops working shortly after I make changes to the "app-component.html" file and ...

Angular 14 debug error: Incorrect base path setting

Whenever I go for a run, I have to specify a starting point such as /pis/ ng serve --serve-path /pis/ Even after following these instructions, nothing seems to load. Can anyone lend a hand with setting a starting point in the ng serve process? ...

Determining the length of an array of objects nested within another object

I received a response from the API called res. The response is in the following format: {"plan":[{"name":"ABC"},{"name":"DEF"}]}. I am attempting to save this response in my TypeScript code as shown below: ...

"CanDeactivate Implementation Failure: Why isn't the Generic Function Being Called

I am currently working on implementing a guard to prevent users from navigating to the login page once they have authenticated themselves. This guard should apply to all page components in my app except for the login page. Below is the code snippet I am u ...

Ways to apply CSS class styles when a button is clicked in Angular

How can I create a button that toggles between light and dark mode when clicked, changing the background color and font color accordingly? I need to add CSS classes .bgdark and .textlight to the 'mainbody' for dark mode. HTML <div cla ...