Encountering the error message "Cannot access variable 'geocodingForm' as it is undefined"

I am currently utilizing reactive forms from Angular Material and encountering an issue. Despite successfully capturing the input value upon submission through console.log, I am facing errors when attempting to store this value in a variable named "address" within the onSubmit method.

Various attempts have been made to resolve this, including:

  • var address=this.geocodingForm.get('input').value
  • var address=this.geocodingForm.value.input

Additionally, trying to switch 'var' to 'let' was also explored.

geocoding.component.html

    <mat-grid-tile colspan='60'>
        <div #gmap class="map"></div>
    </mat-grid-tile>

    <mat-grid-tile colspan='40'>
    <form novalidate [formGroup]="geocodingForm" #gform="ngForm" (ngSubmit)="onSubmit()">
      <h4>Geocoding Service</h4>
      <p>
        <input matInput formControlName="input" placeholder="address" type="text" required>
        <mat-error *ngIf="formErrors.input">{{formErrors.input}}</mat-error>
      </p>
      <button type="submit" mat-button class="background-primary text-floral-white" [disabled]="gform.form.invalid">Submit</button>
    </form>

    </mat-grid-tile>
</mat-grid-list>

geocoding.component.ts

import { Component, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-geocoding',
  templateUrl: './geocoding.component.html',
  styleUrls: ['./geocoding.component.css']
})
export class GeocodingComponent implements OnInit {

  geocodingForm: FormGroup;
  map: google.maps.Map;
  errMess: string;
  mapProp = {};
  @ViewChild('gform', { static: false }) geocodingFormDirective;
  @ViewChild('gmap') gmapElement: any;

  constructor(private fb: FormBuilder) {
    this.createForm();
  }

  ngOnInit() {
    this.mapProp = {
      center: new google.maps.LatLng(18.5793, 73.8143),
      zoom: 15,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    this.map = new google.maps.Map(this.gmapElement.nativeElement, this.mapProp);
  }

  formErrors = {
    'input': ''
  };

  validationMessages = {
    'input': {
      'required': 'Please provide an address'
    }
  };

  createForm() {
    this.geocodingForm = this.fb.group({
      input: ['', [Validators.required]]
    });

    this.geocodingForm.valueChanges
      .subscribe(data => this.onValueChanged(data));

    this.onValueChanged(); 
  }

  onValueChanged(data?: any) { 
    if (!this.geocodingForm) { return; }
    const form = this.geocodingForm;
    for (const field in this.formErrors) {
      if (this.formErrors.hasOwnProperty(field)) {
        this.formErrors[field] = '';
        const control = form.get(field);
        if (control && control.dirty && !control.valid) {
          const messages = this.validationMessages[field];
          for (const key in control.errors) {
            if (control.errors.hasOwnProperty(key)) { 
              this.formErrors[field] += messages[key] + ' ';
            }
          }
        }
      }
    }
  }

   onSubmit() {

    console.log(this.geocodingForm.value.input);
    var geocoder = new google.maps.Geocoder();
    geocodeAddress(geocoder, this.mapProp);

    function geocodeAddress(geocoder, resultsMap) {
      var address=this.geocodingForm.get('input').value;

      geocoder.geocode({'address': address}, function(results, status) {
        if (status === 'OK') {
          resultsMap.setCenter(results[0].geometry.location);
          var marker = new google.maps.Marker({
            map: resultsMap,
            position: results[0].geometry.location
          });
        } else {
          alert('Geocode was not successful for the following reason: ' + status);
        }
      });
    }


    this.geocodingFormDirective.resetForm();
    this.geocodingForm.reset({
      input: ''
    });
  }


}

The main objective is to avoid receiving the error :

Cannot read property 'geocodingForm' of undefined

Answer №1

The reason for this issue is due to your use of traditional function, which causes the value of this to be determined by how the function is called.

Instead, consider using arrow functions like:

geocodeAddress(geocoder, resultsMap){}

& eliminate the nested keyword function

To enhance the code even further, try removing the nested function and create a separate function within the component class

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

Exploring the functioning of Dependency Injection in components that are dynamically loaded

Given the setup of my components and services, with both Module A and B being lazy loaded, I have a scenario where the component container in Module A is dynamically loading Component B1. How does dependency injection work in this case? Does it look for de ...

How can we seamlessly switch between video tags in ReactJS to prevent the dreaded loading black screen from appearing?

Context I have incorporated a video player represented by VideoJS in my project. This player obtains videoData via the socket event video_data from the server and then switches to the received video source. The server operates on-premise, housing all vid ...

Error message in TypeScript: A dynamic property name must be a valid type such as 'string', 'number', 'symbol', or 'any'

Attempting to utilize the computer property name feature in my TypeScript code: import {camelCase} from "lodash"; const camelizeKeys = (obj:any):any => { if (Array.isArray(obj)) { return obj.map(v => camelizeKeys(v)); } else if (ob ...

Utilizing environment variables in the root files of your SvelteKit project: A guide

I have encountered an issue with my SvelteKit project which uses TypeScript and includes a .env file at the root. Additionally, I have added a drizzle.config.ts file at the root directory. The problem arises when I try to import DATABASE_HOST from $env/sta ...

Using React to make an API call without utilizing hooks

Hello, I am currently working on developing a webpart using SharePoint and React. However, I am facing some issues with fetching data from a simple API. export default class Testing100 extends React.Component<ITesting100Props, {}> { constructor(p ...

TypeScript Error 2304: Element 'div' is nowhere to be found - CRA TypeScript Template

I'm experiencing a problem in VSCode while working on the default create-react-app my-app --template typescript project. It seems to not recognize any HTML elements, as I keep getting the error cannot find name xxx, where 'xxx' represents th ...

Navigating the dot notation to uncover the data type of a field within an object

When working with an object type, we can access the type of one of its fields using bracket-string notation. However, why isn't it possible to use dot notation like in JavaScript? Could there be a conflict or some other reason for this limitation? I h ...

Tips for populating a dropdown list with data from the backend and selecting the desired value using Angular

I am currently working on an Angular 8 application that utilizes Material design. My goal is to populate a dropdown list with data retrieved from the backend. The API call code snippet is as follows: returnQrCodes$ : Observable<QRCodeDefinitionSelect ...

Exploring the Various Path Options in Angular 2 Routing

As a newcomer to Angular and Node JS, I am currently working on an application and struggling with how to efficiently navigate between my different components. Users can input the name of a user and add books associated with them When clicking on a book ...

Directive for creating a custom loading indicator in Angular

I have created a custom Angular element directive that displays and hides a loading indicator based on a condition from a service call. The directive is used as an element within another element. While the directive itself works correctly, the issue is tha ...

Implementing Angular 2 module as a nested route

After creating an ngModule called EducationModule that loads a set of navigation items and child routes into a router outlet defined in the root component EducationComponent, everything is functioning perfectly. However, I am facing one issue: I want the f ...

Show every item from a collection on individual lines within an Angular2 module

I am working with an Angular2 component that is responsible for displaying a list of speakers stored in some data. Currently, when I add the code below to my xyz.component.html, it shows the list as comma-separated strings. However, I would like each speak ...

Automatically focus on the button

Encountering an issue where setting focus on a button upon the input key enter event is not working. While setting focus on inputs functions properly, using the same code on a button does not work at all. Sample HTML Component: <form [formGroup]=&apos ...

Display changes in the Angular UI when the cache is refreshed following the API request

Currently, I have integrated Angular service worker to cache my API responses. The configuration used for caching the API is as follows: "dataGroups":[ { "name":"services", "urls":[ "apiUrl" ], ...

Angular Material style focused border

Upgrading from Angular 13 to Angular 15 has been quite the ordeal for me. Many of my designs are broken, and I'm still trying to fix them. The main issues seem to be related to upgrading Angular Material to version 15. Below is a list of all my curr ...

The historyApiFallback feature in webpack-dev-server does not seem to function properly when dealing with multi-level routing scenarios

Currently, I have set historyApiFallback: true to redirect any non-existing URLs to the index page. It works perfectly for first-level routes like localhost:8080/abc. However, when attempting localhost:8080/abc/xyz, an error appears in the browser console: ...

The plugin by chartjs-plugin-crosshair is malfunctioning

Having some trouble with the chartjs-plugin-crosshair - it's not working as expected. Here are the packages I am using: "chart.js": "^3.9.1" "chartjs-plugin-crosshair": "^1.2.0" Seems like there might be an i ...

The mat select option does not have the correct width for the mat

Can someone please help me with this issue? I'm having trouble with the width of the options in a mat-select within a form. When I try to select an option, the width extends to 100% instead of staying within the select box. Here is a snapshot showing ...

Custom TailwindCSS Theme Builder

My goal is to implement a variation of themes and be able to switch between them using tailwind CSS. I came across a tutorial on YouTube regarding this topic in JavaScript youtube video, but I am working with TypeScript and encountering issues with a cus ...

Learn how to utilize interpolation within an *ngIf statement in Angular 2 in order to access local template

Consider the following scenario; <div *ngFor="item of items; let i = index;"> <div *ngIf="variable{{i}}">show if variable{{i}} is true</div> </div> Suppose I have variables named "variable0", "variable1",... Is there a way to ac ...