core.js encountered an error at line 6237: Unable to assign value to property 'area' as it is undefined

HTML: I have created a form but encounter an error when clicking the submit button. Can someone please assist me in identifying the issue?

<h3 class="page-header">Operator Form</h3>
<div class="outer-container">
   <form class="form-section" [formGroup]="operatorForm" (ngSubmit)="save()">
        <!-- <mat-form-field>
            <input matInput type="text" placeholder="Drone Type" formControlName="drone_type" required>
        </mat-form-field> -->
        <mat-form-field>    
            <input matInput type="text" placeholder="Police Station" formControlName="police" readonly>
        </mat-form-field>
        <mat-form-field>
            <input matInput type="text" placeholder="Area" formControlName="area" required>
        </mat-form-field>
        <!-- <mat-form-field>
            <mat-label>Date and Time</mat-label>
             <input matInput [matDatepicker]="picker" formControlName="date" readonly/>
             <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
             <mat-datepicker #picker disabled="false"></mat-datepicker>    
         </mat-form-field> -->
         <mat-form-field>
            <input matInput [ngxMatDatetimePicker]="picker" placeholder="Date and Time" 
                formControlName="date"
                [disabled]="disabled">
            <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
            <ngx-mat-datetime-picker #picker [showSpinners]="showSpinners" [showSeconds]="showSeconds"
               [stepHour]="stepHour" [stepMinute]="stepMinute" [stepSecond]="stepSecond"
               [touchUi]="touchUi" [color]="color" [enableMeridian]="enableMeridian">
            </ngx-mat-datetime-picker>
         </mat-form-field>

        <div style="text-align: right">
            <button mat-raised-button type="submit" [disabled]="operatorForm.invalid" >Submit</button>
        </div>
    </form>
</div>
<div class="spinner" [style.display]="showSpinner ? 'flex' : 'none'">
    <mat-spinner [diameter]="30" ></mat-spinner>
</div>

component.ts:(I am facing an issue with my form upon clicking the submit button. Could you please help me in resolving this? )

payload: any;
ngOnInit(){
   this.operatorForm = new FormGroup({  
     'police': new FormControl(null, Validators.required),
     'area': new FormControl(null, Validators.required),
     'date': new FormControl(null, Validators.required),  
    })
}
save() {
   this.payload.area = this.operatorForm.get('area').value
   this.payload.flightDateTimeStr = this.operatorForm.get('date').value,
   console.log(this.payload)
}

Answer №1

Check out this code snippet for inspiration:


let data ={};
  ngOnInit(){
     this.formData = new FormGroup({
      'name': new FormControl(null, Validators.required),
      'age': new FormControl(null, Validators.required),
      'gender': new FormControl(null, Validators.required),

     })
   }
  
  submit(){
        this.data["name"] = this.formData.get('name').value
        this.data["dateOfBirth"] = this.formData.get('age').value,
      console.log(this.data)
     }

Answer №2

When it comes to injecting keys dynamically in the save method for the payload, there is a specific way to do it properly. Take a look at this code snippet.

payload: any;

save(){
   this.payload = {
      area: this.operatorForm.get('area').value,
      flightDateTimeStr: this.operatorForm.get('date').value,
   } 
}

To cast the object, you can create an interface and typecast the properties accordingly as illustrated below.

export interface PayLoad {
   area: any;
   flightDateTimeStr: any;
}

payload: PayLoad;

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

Material UI is not capable of utilizing Props

I'm having trouble using the Checkbox component from Material UI. Even though I can't seem to use the normal props like defaultChecked or size="small", as it gives me the error TS2769: No overload matches this call. TS2769: No overload ...

Sharing data between parent and child components in Angular using ngrx

Currently, I am implementing @ngrx router and facing a scenario where one of the routes includes child routers for passing route parameters. Here is how it looks: { path: '/browse', component: BrowseComponent, children: [ { path: ':ca ...

Guidelines for iterating through a nested JSON array and extracting a search query in Angular

I'm currently working with a complex nested JSON Array and I need to filter it (based on the name property) according to what the user enters in an input tag, displaying the results as an autocomplete. I've started developing a basic version of t ...

What steps are involved in adding Angular Material to an Angular 2 Application?

I've recently set up an Angular 2 project using Angular CLI. Following the step-by-step guide on Angular Material's website at https://material.angular.io/guide/getting-started, I expected my website to be themed with Angular Material after imple ...

What is the best way to add all the items from an array to a div element?

I am currently facing an issue where only the last object in my array is being added to my div using the code below. How can I modify it to add all objects from the array to my div? ajaxHelper.processRequest((response: Array<Vehicle.Vehicle>) ...

Using Angular to bind a click event to an element after it has been compiled

I am currently developing an application for students using Angular 5. In this application, users can access and view various documents. When a user enters a document, a set of tools, including a marker tool, are displayed. This marker tool allows users to ...

Typescript: Potential null object error when defining a method

I recently encountered an error message stating "Object is possibly null" while working on the changePageSize method in book-store.component.html. It seems like I need to initialize the object within the class, but I'm not familiar with how to do that ...

Encountering a problem during npm installation on Windows 10 while trying to install the Angular CLI globally using the

node -v v4.5.0 npm -v 5.0.1 Is there anybody who encountered a similar problem when trying to install angular-cli on Windows 10? ...

Mastering Angular2: Leveraging TypeScript's Power to Unleash JavaScript ES6 Syntax with

I am having trouble implementing a translation feature using the ng2-translate pipe in my Angular2/Ionic2 app, which is entirely written in JavaScript ES6. However, I have encountered an issue during the setup phase. The code snippets I have found on the ...

Tips for handling catch errors in fetch POST requests in React Native

I am facing an issue with handling errors when making a POST request in React Native. I understand that there is a catch block for network connection errors, but how can I handle errors received from the response when the username or password is incorrec ...

Angular is able to successfully retrieve the current route when it is defined, but

Here's the code snippet I am working with: import { Router } from '@angular/router'; Following that, in my constructor: constructor(router: Router) { console.log(this.router.url); } Upon loading the page, it initially shows the URL a ...

The method TranslateModule.forRoot does not require a specific type argument and produces a ModuleWithProviders type

After upgrading my Angular application from version 5 to version 9, I encountered an error during the build process. The error message stated: "TranslateModule.forRoot returns a ModuleWithProviders type without a generic type argument. Please add a ge ...

The stack property of [object Object] cannot be updated, as it only has a getter method

I can't figure out why I'm receiving this specific error in the Plunker below. Cannot set property stack of [object Object] which has only a getter Access the Plunker here: https://plnkr.co/edit/IP1ssat2Gpu1Cra495u2?p=preview The code causi ...

Navigating a relative path import to the correct `@types` in Typescript

When the browser runs, I require import * as d3 from '../lib/d3.js'; for d3 to be fetched correctly. I have confirmed that this does work as intended. However, the file that contains the above code, let's call it main.js, is generated from ...

The shape-matching subset functionality in Typescript is experiencing issues

One of the key principles of TypeScript is that type checking focuses on the structure of values, a concept known as duck typing or structural typing. This means that only a subset of an object's fields needs to match for it to be considered compatibl ...

In order to effectively manage the output of these loaders, it may be necessary to incorporate an extra loader. This can be achieved by using the

I'm currently working with react typescript and trying to implement a time zone picker using a select component. I attempted to utilize the npm package react-timezone-select, but encountered some console errors: index.js:1 ./node_modules/react-timezo ...

Calculate the total value of an object using Typescript

Here is the data that I have: [Products, Products, Products, Products] 0: Products {product_id: "1", Product_type_id: "11", Subtotal:450, …} 1: Products {product_id: "2", Product_type_id: "22", Subtotal:550, …} 2: Products {product_id: ...

The method Observable.combineLatest is not implemented

One of the features on my website is the Home page, where users can click on Contact me to navigate to the Contact page: home.component.html <div> <a routerLink="/contact" [queryParams]="sendOBj">Contact me</a> </div> home.comp ...

"Encountered an issue with Next-Auth session returning as undefined in getServerSideProps using NextJS version 13.2

When inspecting the code below, session is found to be undefined upon logging from the client side after being transferred from getServerSideProps. import { getServerSession } from 'next-auth/next'; import { authOptions } from './api/auth/[. ...

What is the reason behind the Partial input basic type returning itself?

Snippet of code excerpt: type PartialType<T> = { [P in keyof T]?: T[P]; } I am curious about why the PartialType input basic type (such as string returning string) returns itself instead of throwing an error or an object. // undef => undefined t ...