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

Displaying a component inside a different component

I'm attempting to display components inside another component, but even when I try to include div elements within the component, they don't show up. const DisplayComponent = () => { return ( <div> <DisplayContent ...

Update the Material V4 Style ts file to the latest version, Material V5

I am currently in the process of upgrading from material v4 to v5. The problem I am encountering is related to a styles.ts file that I used to import into my component. Initially, the beginning of the class looked like this: import { defaultFont, prima ...

When an action is clicked within a cell of an Angular Material table row, the (click) event for that row is triggered

Is there a way to activate a modal using a button within a mat-table without triggering the row click event? I've come across Angular Material 2 Table Mat Row Click event also called with button click in Mat Cell but implementing $event.stopPropagatio ...

What is the best way to outline this model using typescript?

Here is a JSON model that I am working with: { "loggers" : { "logger1" : { "name" : "logger1", "level" : "DEBUG", "sub_loggers" :{ "logger1.nested_logger1" : { "name": "lo ...

Adding query parameters to links in Angular 10: A beginner's guide

I'm trying to update a link: <a class="contact-email" href="mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="117268737463656364727a51666370617c7065743f727e7c">[email protected]</a>" ...

Tips for resolving the issue of the symbol ' displaying as &#39 in an Angular 2 application

I am currently working on an Angular application that makes API calls when a name displayed in a grid table is clicked. However, I have encountered an issue where names containing an apostrophe are being displayed incorrectly as &#39 instead. I managed ...

What is the best way to explain the concept of type indexing in TypeScript using its own keys?

I'm still learning TypeScript, so please bear with me if my question sounds basic. Is there a way to specify the index for this type so that it utilizes its own keys rather than just being an object? export type TypeAbCreationModal = { [index: stri ...

How can I customize a currency directive in AngularJS using filters?

My goal is to enhance user experience by allowing input in custom currency values like '1.5M' instead of 1500000, and '1B' instead of 1000000000 on an input form dealing with large numbers. To achieve this, I've created a FormatSer ...

Observing the completion of a subscriber function

Is there a more streamlined way to determine if the subscriber has finished executing or return something and catch it up-stream? Consider the following code snippets: this._subscriptions.push(this._client .getCommandStream(this._command) // R ...

Once app.component's ngOnInit is completed, the child's ngOnInit will be triggered in Angular6

I am working on a project where I need to make an API call in the app.component's initialization process. The child component should then wait for the completion of the app.component's ngOnInit() before proceeding. In app.component.ts: ngOnInit ...

Issue with Angular Material Slide Toggle Binding on Checked Status Not Functioning

It should be a simple task, but I'm struggling to make the checked binding for the slide toggle function properly. (My setup includes angular version 9.1 and material version 9.2.) Here is the HTML snippet: <mat-slide-toggle [checked]="isSlideCh ...

Creating cohesive stories in Storybook with multiple components

I need assistance with my storybook setup. I have four different icon components and I want to create a single story for all of them instead of individual stories. In my AllIcons.stories.tsx file, I currently have the following: The issue I am facing is ...

Is it possible to use conditional logic on child elements in formkit?

I am a bit confused about how this process functions. Currently, I am utilizing schema to create an address auto complete configuration. My goal is to have the option to display or hide the fields for manual input. This is the current appearance of the ...

Showcasing a single object in an IONIC/Angular application using the ngIF directive

I am in need of assistance as I have encountered an issue. Essentially, I am fetching an object from an external API (Strapi) using the GET method, but when attempting to display it on Views with ngIF, it fails to show up. Below is the code snippet: word ...

When adjusting the window size with the <ion-split-pane>, both the menu and router outlet disappear

When I have two ion menus and one main content (router outlet) and resize the page or switch to mobile view, the page appears blank as if the content is missing. Here is the code: <ion-app> <ion-split-pane> <ion-menu side="start" me ...

How should I structure my MySQL tables for efficiently storing a user's preferences in a map format?

My current project involves developing a web application that provides administrators with the ability to manage user information and access within the system. While most user details like name, email, and workID are straightforward, I am facing difficulty ...

What is the purpose of mapping through Object.keys(this) and accessing each property using this[key]?

After reviewing this method, I can't help but wonder why it uses Object.keys(this).map(key => (this as any)[key]). Is there any reason why Object.keys(this).indexOf(type) !== -1 wouldn't work just as well? /** * Checks if validation type is ...

Create a function that will always output an array with the same number of elements as the input

Is there a method to generate a function that specifies "I accept an array of any type, and will return the same type with the same length"? interface FixedLengthArray<T, L extends number> extends Array<T> { length: L; } export function shuf ...

What is the best way to transfer an array to a different component?

I have an array called FidId that consists of strings, and I am looking to pass this array to another component for use. public AddSelection(layer: VectorLayer, map:Map){ this.vectorSource = layer; //start select var FidId:string[] = []; ...

Struggling with sluggish performance on a certain project within VS Code

My experience with VS code has been excellent over the years, but I recently encountered a problem in one of my projects that caused a significant slowdown in performance. Strangely, other projects are working fine without any issues on VS code. I suspect ...