Error in Angular Google Maps Component: Unable to access the 'nativeElement' property as it is undefined

I am currently working on creating an autofill input for AGM. Everything seems to be going smoothly, but I encountered an error when trying to integrate the component (app-agm-input) into my app.component.html:

https://i.stack.imgur.com/mDtSA.png

Here is a snippet of my component:

import {
    Component,
    OnInit,
    ViewChild,
    ElementRef,
    NgZone,
    Input
} from "@angular/core";
import { MapsAPILoader } from "@agm/core";
import {} from "@types/googlemaps";

@Component({
    selector: "app-agm-input",
    templateUrl: "./agm-input.component.html",
    styles: []
})
export class AgmInputComponent implements OnInit {
    @ViewChild("agmInput") public searchElement: ElementRef;

    @Input() placeholder: string;

    constructor(private mapsAPILoader: MapsAPILoader, private ngZone: NgZone) {}

    ngOnInit() {
        this.mapsAPILoader.load().then(() => {
            let autocomplete = new google.maps.places.Autocomplete(
            this.searchElement.nativeElement,
            { types: ["address"] }
        );

        autocomplete.addListener("place_changed", () => {
            this.ngZone.run(() => {
                let place: google.maps.places.PlaceResult = autocomplete.getPlace();

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

Below is a glimpse at how my module is set up:

import { NgModule } from "@angular/core";
import { AgmInputComponent } from "./agm-input.component";
import { SharedModule } from "../../shared.module";
import { AgmCoreModule } from "@agm/core";

@NgModule({
    imports: [
        SharedModule,
        AgmCoreModule.forRoot({
            apiKey: "**key**",
            libraries: ["places"]
        })
    ],
    declarations: [AgmInputComponent],
    exports: [AgmInputComponent]
})
export class AgmInputModule {}

Please Note: The API key has been removed for review purposes.

This is what my component's HTML file looks like:

<input class="input" type="search" placeholder="{{placeholder}}" autocorrect="off" autocapitalize="off" spellcheck="off" #agmSearch>

Answer №1

You have mentioned the incorrect variable name

To fix this issue, update your code to:

    @ViewChild("agmSearch") public searchElement: ElementRef;

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

What is the process for creating URL query parameters?

What is the process for generating parameters after node?_=xxxxxx? If I am using a Python script to access the URL, how can I retrieve these parameters? edit: I apologize for not providing enough information. This is my first post as a novice. I am atte ...

Using AJAX to call a PHP function within a PHP script

I have successfully implemented an AJAX file that can execute content from a PHP file. However, my concern is how to specifically call a particular function within the PHP file if there are multiple functions present. Below is my current AJAX code: $(doc ...

Issues with embedding iframes

I have a webpage with an embedded iframe that is making ajax requests. However, when I click on a link, it opens in the iframe instead of the main window. I tried using this JavaScript code: window.parent.location.href = url of link but it didn't wo ...

Verify the information received from the ajax call to PHP

After incorporating all the guidance I received, I performed an update and here are the results: UPDATED CODE: $(document).ready(function(){ $("#submit").submit(function(e){ e.preventDefault(); var username = $("#username").val(); var ...

How can I utilize a variable to define the key for the template HTML property in Angular 7?

Is there a method in Angular 7+ that allows me to incorporate a variable as the template html property key? I am trying to achieve something like the following: <path [attr.data-**<use-variable-here>**]="edge.id"></path> ...

Type inference and the extends clause in TypeScript 4.6 for conditional types

My focus was on TypeScript 4.7 when I created the following types: const routes = { foo: '/foo/:paramFoo', bar: '/bar/:paramFoo/:paramBar', baz: '/baz/baz2/:paramFoo/:paramBar', } as const; type Routes = typeof routes; ...

Having trouble retrieving a specific value from a json object

Below is the JSON data that I am dealing with: var data = {200x200: "url1", 400x400: "url2", 800x800: "url3"}; After stringifying the object and attempting to access "200x200," I encountered an issue: undefined data = JSON.stringify(data); //data = ...

Employing v-btn for navigating to a different route depending on whether a specific condition is satisfied

Is there a way to prevent this button from redirecting to the specified URL? I want to implement a validation check in my method, and if it fails, I need to stop this button from performing any action. Any suggestions or assistance would be highly apprec ...

Implementing two background images and dynamically adjusting their transparency

With the challenge of loading two fixed body background-images, both set to cover, I encountered a dilemma. The text on the page was extending below and scrolling, along with top and bottom navigation icons. As expected, the second background covered the f ...

Access the latest data within Sails' Waterline prior to the update process

When using Sails' Waterline, I am tasked with comparing the previous value to the new one and assigning a new attribute based on certain conditions. For instance: beforeUpdate: function(newValues, callback) { if(/* currentValues */.age > newVal ...

Tips for managing large amounts of data retrieval from an API

As a beginner, I am attempting to retrieve data from an API and display it using the v-for directive. However, this process is causing my app to lag. It freezes when new data is fetched or when I search within the list. The following code snippet shows whe ...

How can I transfer a collection of JSON objects from JavaScript to C#?

Feeling a bit confused here. I have some Javascript code that will generate JSON data like the following: {type:"book" , author: "Lian", Publisher: "ABC"} {type:"Newspaper", author: "Noke"} This is just one example, I actually have more data than thi ...

Saving solely the content of an HTML list element in a JavaScript array, excluding the image source

One issue I am facing is with an unordered list in HTML which contains items like <ul id="sortable"> <li class="ui-state-default"><img src="images/john.jpg">John</li> <li class="ui-state-default"><img src="images/lisa.jpg ...

What is the best way to use JavaScript to emphasize the searched text in a textbox?

My application uses JavaScript and I am looking to both highlight the search element and keep the cursor in the textbox positioned at the search item. Can anyone suggest a way to accomplish this using JavaScript? ...

The request in Node.js was terminated

While using express and body-parser to transfer a large amount of data from one server to another, I encountered the following exception after some time: { "message": "request aborted", "code": "ECONNABORTED", "expected": 99010, "length": ...

Tips on expanding an interface of a subclass

Using the latest versions of TypeScript and ReactJS together has presented a challenge when it comes to extending classes and their interfaces. To address this issue for several form elements that share common validation methods, I have created a BaseComp ...

Facing an issue with sending data in AJAX Post request to Django View

I have been trying to send data from the frontend to the backend of my website using AJAX. Below is the post request view in my Django views: def post(self, request): id_ = request.GET.get('teacherID', None) print(id_) args = {} ...

What is the best way to search for items using only a portion of a phone number or typing a name in any case (uppercase, lowercase) and still get accurate results?

let contacts = [ { name: 'John', phone: 987654 }, { name: 'Sara', phone: 654321 } ] I am developing a contact manager app with various functions to manage contacts. Add new contac ...

Step-by-step Guide on Installing VueJs Medium Editor

After spending countless hours trying to install Medium Editor in VueJs, I finally got it working on a single page vuejs. However, I hit a roadblock when trying to make it work with the webpack file structure: ├── main.js # app en ...

JavaScript can retrieve the default page name that is hidden within the browser's URL

When a URL is entered without a specific file name at the end, such as "www.google.com," the server typically serves a default file like "index.html" or "default.aspx." In this scenario, if the browser displays "www.google.com," I am looking to extract the ...