The error message "TypeError: Unable to retrieve the 'Name' property of an object that is undefined" is commonly associated with

Hey there, I'm struggling to submit a form with just one field using Angular 7. However, I keep encountering this error specifically on the Input line:

ERROR TypeError: Cannot read property 'Name' of undefined

This is how my HTML code looks like:

<form #form="ngForm" autocomplete="off" (submit)="onSubmit(form)">
    <input type="hidden" name="Id" [value]="service.formData.Id">
    <div class="form-group" >
        <div class="input-group" *ngIf="service">
            <div class="input-group-prepend">
                <div class="input-group-text bg.white">
                        <i class="fas fa-user" [class.green-icon]="Name.valid" [class.red-icon]="Name.invalid && Name.touched"></i>
                </div>
            </div>
            <input name="Name" #Name="ngModel" [(ngModel)]="service.formData.Name" class="form-control" placeholder="Student Name" required maxlength="50">
        </div>
    </div>
    <hr>
    <div class="form-group">
        <button class="btn btn-success btn-lg btn-block" type="submit"><i class="fas fa-database"></i> Submit</button>
    </div>
</form>

Here is my component setup:

import { Component, OnInit } from '@angular/core';
import { StudentDetailService } from 'src/app/shared/student-detail.service';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'app-student-detail',
  templateUrl: './student-detail.component.html',
  styles: []
})
export class StudentDetailComponent implements OnInit {

  constructor(private service:StudentDetailService) { }

  ngOnInit() {
    this.resetForm();
  }

  resetForm(form?:NgForm)
  {
    if(form !=null){
      form.resetForm();
      this.service.formData = {
        Id :0,
        Name :'',
        StudentSubjects :null
      }
    }

  }

  onSubmit(form:NgForm)
  {
    this.service.postStudentDetail(form.value).subscribe(
      res => {
        this.resetForm(form);
      },
      err => {
        console.log(err)
      }
    );
  }
}

And here's my Service implementation:

import { Injectable } from '@angular/core';
import { StudentDetail } from './student-detail.model';
import {HttpClient} from "@angular/common/http";

@Injectable({
  providedIn: 'root'
})
export class StudentDetailService {
  formData :StudentDetail;
  readonly rootURL = 'http://localhost:31047/api';

  constructor(private http: HttpClient) { }

  postStudentDetail(formData:StudentDetail)
  {
    return this.http.post(this.rootURL+'/StudentDetail',formData)
  }
}

I've noticed that the "service" variable in the component seems to be returning null, even though it appears fine in the ngOnInit() function. I attempted to use the *ngIf="service" command without success. Any idea why this error keeps popping up? Appreciate any help or insights!

Answer №1

  1. Make sure to check if the Name property of the service.formData is not null before trying to read it.

    Instead of using *ngIf="service", try using *nfIf="service.formData"

  2. In the resetForm method, ensure that you initialize the this.service.formData only if the argument is not null. Also, in the ngOnInit() method, remember to call the resetForm method with parameters to properly initialize the formData.

Answer №2

Make sure to initialize the formData object in your component when it is first initialized.

Prior to calling resetForm in the ngOnInit lifecycle hook, be sure to set up the initial values for formData.

ngOnInit() {
this.service.formData = {
        Id: 0,
        Name: '',
        StudentSubjects: null
      }
this.resetForm();
}

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

A step-by-step guide to resolving the TS2345 compilation error during your TypeScript upgrade from version 4.7 to 4.8

We encountered a compiling error after upgrading from TypeScript 4.7.4 to a newer version (specifically, 4.8.4). This error was not present in our codebase when using 4.7.4. To pinpoint the issue, I have extracted the error into a small code snippet. When ...

Using Javascript to parse SOAP responses

Currently, I am working on a Meteor application that requires data consumption from both REST and SOAP APIs. The SOAP service is accessed using the soap package, which functions properly. However, I am facing challenges with the format of the returned data ...

Having issues with narrowing down a TypeScript class

Check out this simplified code snippet: class Thing<InState extends boolean = boolean> { public inState(): this is Thing<true> { return true; } } const y = new Thing(); if (y.inState()) { y } When I hover over y in ...

Obtain a collection of custom objects through an HTTP GET request to be utilized in an Angular 2 application

I am currently grappling with the task of efficiently retrieving a list of custom objects and displaying their contents using an HTML file. Here is a simplified version of the HTTP GET method that I am working with: [HttpGet("/atr/testing")] public List& ...

Manipulating array objects by replacing values in Typescript

Attempted two different methods to obtain a partial summary within each array object, but unfortunately, both were unsuccessful. var arr = [ { "value": 10, "newBalance": 0 }, { "value": -10, "newBalance": 0 }, ...

Error TS2488 in React TypeScript: The data type 'IStateTypes' is required to have a method called '[Symbol.iterator]()' that returns an iterator

At the moment, I am working on implementing a global state in React Hooks but have run into an issue. https://i.stack.imgur.com/DN83K.png The current problem I'm facing is with [Symbol.iterator](. I am uncertain about how to resolve this as I am in ...

The clash of dependencies in Transloco

Currently, I am in the process of integrating the Transloco package into my Angular Ionic project that I compile using VSCode. My Angular version is 13.3.0. Upon executing the installation command: ng add @ngneat/transloco I encounter a series of terminal ...

Delivering JSON-formatted API responses from C# to Angular

When retrieving data from an API and attempting to parse it as JSON in Angular ts, the following error occurs: "Argument of type 'Subscription' is not assignable to parameter of type 'string'". The desired outcome is to receive the JSON ...

Tips for passing an object as an argument to a function with optional object properties in TypeScript

Consider a scenario where I have a function in my TypeScript API that interacts with a database. export const getClientByEmailOrId = async (data: { email: any, id: any }) => { return knex(tableName) .first() .modify((x: any) => { if ( ...

Using Angular to make a request to a NodeJS+Express server for a simple GET operation

I need help with making a successful GET request from my Angular component to a NodeJS+Express server. someComponent.ts console.log("Before"); // send to server console.log(this.http.get('/email').map((res:Response) => { console.log(" ...

refresh recaptcha version 2 for Angular 6

Recently, I started working with Angular 6 and added a recaptcha feature to my registration page. After the form is submitted, I need to reset the recaptcha value in case someone wants to submit the form again. Below is the code snippet I am using within ...

Tips for sending an Angular http post request including both data and an image:

When making a post request in Angular, I typically send data (such as 'product' data) using an object like this: product: any = {}; // filled with properties (code, barcode, name, description...) and then include it in the request: return this.h ...

What is the proper way to define the scope for invoking the Google People API using JavaScript?

I am attempting to display a list of directory people from my Google account. export class People { private auth: Auth.OAuth2Client; private initialized: boolean = false; private accessToken: string; constructor(private readonly clientEmail: strin ...

Designing a grid that adjusts dynamically using Kendo UI for Angular

The Kendo UI for Angular framework offers a grid component that can be configured in the following manner: <kendo-grid [data]="gridData" [height]="410"> <kendo-grid-column field="ProductID" title="ID" width="40"> </k ...

Sharing functions between Angular components

Check out my problem statement: https://stackblitz.com/edit/angular-jk8dsj I'm facing two challenges with this assignment: I need to dynamically add elements in the app.component when clicking a button in the key-value.component. I've tried ...

The value specified as type '{ value: BigNumber; }' cannot be assigned to the parameter type 'Overrides & { from?: string | Promise<string> | undefined; }'

I am currently working on a smart contract using Solidity (version 0.8.0) at my buildspace project. Below is a snippet of my code written in TypeScript (4.5.x)/JavaScript and Node.js 16.13.x: ... const waveContractFactory = await hre.ethers.getContractFact ...

I possess a JSON array object and need to identify and extract the array objects that contain a specific child node

const jsonArray = { "squadName": "Super hero squad", "homeTown": "Metro City", "formed": 2016, "secretBase": "Super tower", "active": true, "members": [ { "name": "Molecule Man", "age": 29, "secretIdent ...

Latitude and longitude coordinates matrix

Lately in my project, I have been working with a database that stores latitudes and longitudes for various addresses. My goal is to extract this data from the database and display it on Google Maps with routes using Angular 2. Unfortunately, I've enco ...

What is the best way to test a function that returns a JSX element in a unit test

I created a function that takes in a parameter and returns a JSX.Element //title.tsx export const getTitle = (pageTitle: string) => { return <title> {pageTitle} </title>; } This is how I am currently testing it: describe('Title c ...

What could be causing the issue with the variable appearing as undefined in

My class has a property: public requestLoadPersonal: Personal[] = []; As well as a method: private filterByGender(selectedValue: any): void { console.log(this.requestLoadPersonal); this.requestLoadPersonal = this.requestLoadPersonal.filter( ...