Leverage the nativeElement property within two separate components

Encountering an error in the autocomplete feature for Angular Maps (AGM), which reads:

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'nativeElement' of undefined
TypeError: Cannot read property 'nativeElement' of undefined

This issue arises when utilizing ElementRef within Angular, particularly with

public searchElement: ElementRef;
.

The error occurs at this line:

  public latitude: number;
  public longitude: number;
  public searchControl: FormControl;
  public zoom: number;

  @ViewChild("search")
  public searchElementRef: ElementRef;

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

  ngOnInit() {
    // Setting default values for Google Maps
    this.zoom = 4;
    this.latitude = 39.8282;
    this.longitude = -98.5795;

    // Creating a search FormControl
    this.searchControl = new FormControl();

    // Setting current position
    this.setCurrentPosition();

    // Loading Places Autocomplete
    this.mapsAPILoader.load().then(() => {
      let autocomplete = new google.maps.places.Autocomplete(this.searchElementRef.nativeElement, {
        types: ["address"]
      });
      autocomplete.addListener("place_changed", () => {
        this.ngZone.run(() => {
          // Retrieving the place result
          let place: google.maps.places.PlaceResult = autocomplete.getPlace();

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

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

In my view component

  <div class="form-group">
    <input placeholder="search for location" autocorrect="off" autocapitalize="off" spellcheck="off" type="text" class="form-control" #search [formControl]="searchControl">
  </div>
  <agm-map [latitude]="latitude" [longitude]="longitude" [scrollwheel]="false" [zoom]="zoom">
    <agm-marker [latitude]="latitude" [longitude]="longitude"></agm-marker>
  </agm-map>

I am using this setup in two components; it functions correctly in one but throws the aforementioned error in the other. I have attempted to use different names for the element reference without success.

Answer №1

It is recommended to define a variable like

@ViewChild("search") public searchElementRef: ElementRef;

instead of using

public searchElement: ElementRef

This way, the searchElement variable will refer to the template reference search specified in your template as (#search) for the input element.

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

Challenges encountered with wrapper component functionality in Angular 6

I am currently working on creating a wrapper component for the saturn-datepicker in Angular. My plan is to use this wrapper component in multiple applications now and potentially switch it out with another datepicker in the future. Although new to Angular, ...

Prevent all dates from being selected except for the last day of every month in the Angular Material Calendar component

Is it possible to restrict all dates except the final day of each month with Angular Material? I need users to only be able to select this particular date. There is a [matDatepickerFilter] property, but it seems to work only for a specific list of dates. ...

Angular 2 Custom Pipe Magic

I'm brand new to using the Angular 2 framework and I'm attempting to create a custom filter. app.component.ts import {Component} from 'angular2/core'; import {HTTP_PROVIDERS} from 'angular2/http'; @Component({ selector: ...

App-Root in Angular 2 not loading properly in ExpressJS route

As a newcomer to NodeJS and Express, I am trying to create a simple '/' route that points to Angular's default index.html file located at client/src/index.html. This file contains the app-root tag. While the '/' route successfully ...

Utilizing Lodash in TypeScript to merge various arrays into one cohesive array while executing computations on each individual element

I am working with a Record<string, number[][]> and attempting to perform calculations on these values. Here is an example input: const input1 = { key1: [ [2002, 10], [2003, 50], ], }; const input2 = { key ...

Try using ngFor within the insertAdjacentHTML method

When a user clicks, I dynamically attach an element inside a template like this: this.optionValue = []; youClickMe(){ var moreput = ''; moreput += '<select">'; moreput += '<option *ngFor="let lup of opti ...

How to apply conditional styling to text using Angular2

I need to display a list of objects that contain names and numbers. The color of the name should change based on the number associated with it - red for 1, blue for 2, green for 3, and orange for 4. My template currently looks like this: <p *ngFor="l ...

Create an array form with the first input at index 0 filled out

Currently, I am in the process of developing a form that allows users to update, add, delete, and edit entries using Angular 2 and reactive forms. To achieve this, I have utilized a form builder array to dynamically add input controls to the form array. Ev ...

Ways to retrieve "this" while utilizing a service for handling HTTP response errors

I have a basic notification system in place: @Injectable({ providedIn: 'root', }) export class NotificationService { constructor(private snackBar: MatSnackBar) {} public showNotification(message: string, style: string = 'success' ...

Declare the push method within the Countly.q array in a TypeScript declaration file

Is there a way to declare Countly push add_event method in the following manner? Countly.q.push(['add_event',{ "key":"action_open_web", }]); I attempted to do this inside a declaration file (.d.ts) but it did not work. Here ...

"Maximizing the potential of Bootstrap and Ionic within Angular: A step-by

I have an Angular project created using the Ionic framework, but I also want to incorporate Bootstrap. How can I achieve this? I have installed Bootstrap and made changes to the angular.json file as shown below: "styles": [ { ...

Error encountered with Angular version 4: Unexpected token export

Upon starting the app with the command ng serve, I encountered an error in the console: VM1018:2297 Uncaught SyntaxError: Unexpected token export at eval (<anonymous>) at webpackJsonp.../../../../script-loader/addScript.js.mod ...

Each styled component will yield the respective type definitions using (@types/styled-components)

Encountering a strange problem with styled-components in VSCode. Every component from styled-components is returning 'any'. I had it working previously, but unsure when it stopped and I can't spot the issue causing all components to return ...

Filtering an array using criteria: A step-by-step guide

Currently, I am developing a system for Role Based permissions that involves working with arrays. Here is an example of the array structure I have: let Roles = { [ { model: 'user', property: 'find', permission: 'allow' ...

Angular 14: Deleting an item from a FormArray triggers unintended form submission due to Angular animation

After beginning to create animations for my app, I observed that deleting an element from a FormArray triggers a form submission. Custom form controls were developed using ControlValueAccessor, and certain FormGroups are passed through @Inputs. The animati ...

Encountering an issue with TypeScript error code TS2322 when trying to assign a className to the @

Encountering a typescript error when trying to apply a className to a Box element. Interestingly, the same code works on other developers' machines with almost identical configurations. Current dependencies: "@material-ui/core": "4.11. ...

Encountering an error of ExpressionChangedAfterItHasBeenCheckedError while trying to refresh the

I'm encountering an issue that I need help with: https://i.stack.imgur.com/4M54x.png whenever I attempt to update the view using *ngIf to toggle on an icon display. This is what my .ts file looks like: @Component({ selector: 'app-orders&ap ...

What is the best way to filter and sort a nested tree Array in javascript?

Looking to filter and sort a nested tree object for a menu If the status for sorting and filtering is true, how do I proceed? const items = [{ name: "a1", id: 1, sort: 1, status: true, children: [{ name: "a2", id: 2, ...

Generic partial application fails type checking when passing a varargs function argument

Here is a combinator I've developed that converts a function with multiple arguments into one that can be partially applied: type Tuple = any[]; const partial = <A extends Tuple, B extends Tuple, C> (f: (...args: (A & B)[]) => C, ...a ...

Module not found in Typescript

Filter.ts, mustache.js and redux.3.5.2.js are all located in the same directory (/Scripts). The code snippet within Filter.ts is as follows: ///<reference path="./typings/mustache.d.ts" /> import Mustache = require("mustache"); import Redux = requir ...