"Encountering issues with Angular2's FormBuilder and accessing nested object properties,

As I dip my toes into TypeScript and Angular2, I find myself grappling with a nested object structure in an API. My goal is to align my model closely with the API resource. Here's how I've defined the "Inquiry" model in TypeScript:

// inquiry.ts
export class Inquiry {
  name: {
    first: string,
    last: string
  };
  email: string;
  phone: string;
  question: string;
}

This is what my form component looks like:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { InquireService } from './inquire.service';
import { Inquiry } from './inquiry';

@Component({
  selector: 'inquire-form',
  templateUrl: './inquire-form.component.html'
})
export class InquireFormComponent implements OnInit {
  inquiryForm: FormGroup;
  inquiry = new Inquiry;

  constructor(
    private formBuilder: FormBuilder,
    private inquireService: InquireService) {}

  ngOnInit(): void {
    this.buildForm();
  }

  buildForm(): void {
    this.inquiryForm = this.formBuilder.group({
      'firstName': [
        this.inquiry.name.first, [
          Validators.required,
          Validators.minLength(2),
          Validators.maxLength(50)
        ]
      ], ...
  }
}

Upon hitting my route, I encounter the following error:

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

When I check this.inquiry.name, it indeed returns undefined. However, I'm puzzled as to why. Where could I be going wrong?

Answer №1

The issue stems from the fact that none of the properties in the Inquiry object are initialized, resulting in all default values being set to undefined. This causes problems especially with the essential name property, which is not initialized, leading to failures when trying to access its subproperties (first or last).

You can address this by either setting it in a constructor:

constructor() {
    this.name = {} as any; // too lazy to give first/last properties
}

or initializing it in the declaration:

class Inquiry {
    name = {} as {
        first: string,
        last: string
    };
    email: string;
    phone: string;
    question: string;
}

Alternatively, if you want to explicitly define the type without relying on inference:

class Inquiry {
    name: {
        first: string,
        last: string
    } = {} as any;
    email: string;
    phone: string;
    question: string;
}

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

What is the significance of the 'this' context type void not being assignable to type rule?

Currently, I am conducting tests using Typescript to explore the feasibility of a project I have in mind. In one of my functions, I need to specify the type of 'this' as a class. While it technically works, I continue to encounter an error messag ...

Tips for closing print window dialog during Protractor testing

Currently, I am performing end-to-end testing using protractor. During a specific test, I need to verify if the print button is successfully creating a PDF. When the test clicks on the button, it triggers a print window dialog as shown below: https://i.st ...

Modify the width of the <nz-date-picker> component from Ng-Zorro

Currently using Ng-Zorro for my template styling and working on implementing a date picker that I want to align perfectly with the dropdown menu above it. I would like to adjust the width of the date-picker manually within the template, but after visiting ...

Initial 16 characters of the deciphered message are nonsensical

In a specific scenario, I encounter data encryption from the API followed by decryption in TypeScript. I have utilized CryptoJS for decryption in TypeScript. Below is the decryption code snippet: decrypt(source: string, iv: string): string { var key = envi ...

Maintaining ongoing subscriptions using rxjs in Angular 5

As a newcomer to rxjs in Angular 5, I find it a bit challenging to articulate my question, but I am hopeful for some guidance. I frequently encounter the same setup: Multiple Components to display identical data A single Service for accessing the data ...

Guide to developing a versatile Icon Wrapper component for FontAwesome Icons in React that adapts to changing needs

I'm looking to develop a customized React Icon-Component where I can simply input the icon name as a string and have the icon display automatically. After following the guidelines provided here: https://fontawesome.com/docs/web/use-with/react/add-ico ...

When running jest unit tests, an error is thrown stating that includes() and toLowerCase are not functions

MyComponent.js contains both toLowerCase and includes methods on the props. However, when attempting to perform unit testing on MyComponent, I encounter an issue where the functions toLowerCase() and includes() are not recognized as valid. Within MyCompon ...

Navigating to a child route from a parent component in Angular using the navigate method: A step-by-step guide

Here is the code snippet for my HTML routerLink: <a [routerLink]="['create']">Create</a> - it's working just fine. When I try to call the same on a button click, it doesn't work.. navigateTo(page) { this.router.na ...

Adjusting ngClass dynamically as values change

Currently, I am facing a situation where I want to dynamically add a class to my view using ngClass based on changes in the output value. The output value is dependent on the response received from an API, and I am fetching data from the endpoint every sec ...

Troubleshooting Problem with Next.js 13 Integration, Supabase, and Server Actions in layout.tsx

I'm currently developing a Next.js 13 application and experimenting with managing user authentication through Supabase. I've encountered some challenges when attempting to verify if a user is logged in using an asynchronous function within my lay ...

The Gatsby + Typescript project is reporting that the module with the name "*.module.scss" does not have any exported members

I've recently gone through Gatsby's demo project in their documentation (which is long overdue for an update). I've carefully followed the instructions provided here: I've included an index.d.ts file in the /src directory of my project ...

The reload button retains functionality while being present within an Angular2 form, allowing for a seamless user experience. The

After some observation, I have realized that when a button is placed inside a form but has no connection or function related to the form, such as a back or cancel button, it unexpectedly reloads the entire page. For instance, let's consider having ...

What is the best way to remove an exported JavaScript file from Node.js?

In my Node.js library package called "OasisLib," there is a file named TypeGenerator.ts. The specific logic within the file is not crucial, but it requires access to files in the filesystem during the project build process. To achieve this, we utilized let ...

NgbHighlight now allows for one highlight element per line

I am currently utilizing NgbHighlight to allow users to search within a list. However, I am facing an issue with the highlighting of search results. My intention is to highlight only the first match in the list. I am sticking to the basic implementation ...

Troubleshooting problem with sorting in Angular 4 material header

Using Angular 4 material for a table has presented me with two issues: 1. When sorting a table, it displays the description of the sorting order in the header. I would like to remove this. It displays "Sorted by ascending order" here. The ngx modal theme ...

The types for Cypress are not being detected by my Angular tsconfig file

I'm facing an issue with my Angular tsconfig not detecting the Cypress 12.3 types. I have tried numerous solutions to resolve this problem, but nothing seems to work, except for the extreme measure of starting the project over, which I think might sol ...

In TypeScript, make sure to verify the type of an object to avoid any potential compilation errors stemming

Here is the code snippet: export default class App { el: HTMLElement; constructor(el: string | HTMLElement) { if (typeof el === "string") { this.el = document.getElementById(el); } if (typeof el === typeof this.el) { t ...

How to implement a reusable module with distinct routes in Angular

In my current angular project, we have various menus labeled A, B, C, D, and E that all utilize the same module. Specifically, menus A, C, and E use the same component/module. My goal is to ensure that when I am on menu A and then click on menu C, the sa ...

Ways to retrieve and bind data using onMounted in VueJS

Loading Data in Test.vue Component <template> <li v-for="item in masterCompany" v-bind:key="item.id"> {{ item.displayName }} </li> </template> <script> import Test from "../hooks/Test.hook" ...

When attempting to compile the building project following the upgrade to Angular 9, an error message is displayed stating "Unable to access property 'length' as it is undefined

I'm currently in the process of updating my Angular 9 project by following the migration guide on update.angular.io. After running ng update @angular/core @angular/cli, I encountered an error "ERROR in Cannot read property 'length' of undefi ...