Angular forms encountered an error "cannot read property 'street' of undefined" because the property 'street' is

Exploring angular 6 with spring boot and encountering an issue with nested classes. Below is my code snippet but I'm facing difficulties in displaying users and getting an error. Can someone assist me?

 export  class Address {

street: string;
    suite: string;
  city: string;
 zipcode: string;


}
    import {Address} from './address';


    export class User {

     id: number;
     name: string;
     email: string;
     address: Address;
     phone: string;
     website: string;

    }

Sharing my html code below:

 <form (ngSubmit)="onSubmit()" >
    <div class="form-group">
      <label for="id">User Id</label>
      <input type="text"   class="form-control"  id="id"   required [(ngModel)]="users.id" name="id">

    </div>
    <div class="form-group">
      <label for="name">Name</label>
      <input type="text"  class="form-control"  id="name"  required [(ngModel)]="users.name" name="name">
    </div>
    <div class="form-group">
      <label for="email">Email</label>
      <input type="email"  class="form-control"  id="email" required [(ngModel)]="users.email"  name="email">
    </div>

    <div class="form-group">
      <label for ="street"  >Address street</label>
      <input  type="text"  class="form-control" id="street"  required [(ngModel)]="users.address.street"  name="street">
    </div>

Answer №1

Ensure that in your classroom setting, you establish the address as a concrete instance. By default, the address will remain undefined unless specified otherwise. You can achieve this by initializing it within the constructor method, as shown below:

 export class User {

  constructor() {
    this.address = new Address()
  }

  id: number;
  name: string;
  email: string;
  address: Address;
  phone: string;
  website: string;
}

I trust this explanation is beneficial to you!

Answer №2

In order to ensure functionality, it is crucial to have a users property properly defined within your Component Class:

import { Component } from '@angular/core';

@Component({...})
export class YourComponent  {
  users = {
    id: '',
    address: {}
  };
}

For reference, you can check out this Sample StackBlitz.

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

Using Typescript to determine the data types based on the specific object keys

Imagine having a type defined as: type Foo = { foo: number; bar: string; baz: boolean; } The goal is to create a type Buzz that can determine the value type for a specific key, such as: const abc: Buzz<Foo> = { key: 'foo', form ...

Error in Angular 7 Reactive Forms: "No value accessor available for form control without a specified name attribute"

I'm encountering issues with some form fields while using reactive forms in Angular. Any insights on why this might be happening would be greatly appreciated. Just started working with Angular and Material 7, if that's relevant. An interesting ...

Filter through the array of objects using the title key

I'm attempting to extract specific data by filtering the 'page_title' key. Below is a snippet of my JSON object: { "page_components": [ { "page_title": "My Account", "row_block": [ { "heading": "", "sub_headi ...

Obtain the Enum's Name in TypeScript as a String

I am currently looking for a solution to transform the name of an enum into a string format. Suppose I have the following Response enum, how can I obtain or convert 'Response' into a string? One of my functions accepts any enum as input and requi ...

The parameter cannot be assigned the readonly type 'X' in this context

I encountered an issue with a third-party library where the class structure changed. Initially, it was defined as: export class Foo { field: X[]; …. } In my code, I was working with this type: print(foo.field) After updating to a new version, the c ...

Is there a simple method to eliminate devDependencies from the ultimate package using esbuild?

My current challenge involves using esbuild to package my lambda functions. However, during the build generation for deployment, I encounter an alert indicating that the package size exceeds the limit, as shown in the image below. File too large In explo ...

Exploring Angular observables: Tips for gathering specific fields from a nested array within an object into a new array

I am working on parsing a JSON object and extracting specific fields to create their own array. My goal is to loop through the provided object and gather the 'appSupportedId' values into a separate array. An issue has arisen, leading to an ERRO ...

Tips for utilizing specific backend properties exclusively in an ngrx store

As I embark on incorporating ngrx into a new enterprise Angular application, I am faced with the task of loading data into the store using a simple effect that triggers a service call. The response from the server upon successfully calling this service co ...

Incorporating the Chevron icon into the ngx-bootstrap accordion

I'm facing an issue with changing the chevron orientation from UP to DOWN when clicking on the accordion. No matter what solution I attempt, it always seems to return true. I've also tried referring to other examples like this one. < ...

Incorrect indentation when using the latest Prettier in conjunction with Angular 17 and VS Code

Utilizing the most recent version of prettier with the following configuration file: { "arrowParens": "always", "bracketSameLine": true, "bracketSpacing": true, "semi": true, "experiment ...

The type does not have a property named 'defaultProps'

I have a Typescript React class component structured like this: import React, { Component } from 'react'; interface Props { bar?: boolean; } const defaultProps: Partial<Props> = { bar: false, }; class Foo extends Component<Props& ...

Angular 6 Progressive Web App Error: JSON Parsing Issue at Beginning of JSON Data

Recently, I updated an Angular application from version 5 to 6. Previously, the service worker was functioning properly. However, after building the production build using 'ng build -- prod', I encountered the following error... Error:- Unexpe ...

Importing Angular Circular Module for your project

I have encountered a situation where I have two Modules with components that need to use each other. This means that I have to import "word" in "test" and "test" in "word" which results in an error. How can I resolve this issue? Module "test": @NgModu ...

Incorporating an additional ion-item alongside the existing one instead of substituting it

I am retrieving a list of questions from an API with pagination. I have a button that triggers a function to load the next page of questions. Instead of replacing the previous page, I want to append the new questions below the existing ones. Here is my cur ...

Ahead of Time compiled Angular applications utilize computed object/map/dictionary keys for optimal performance

In my Angular project, we are exploring the idea of defining routes as Enums and then declaring the specific routes that they should point to. These Enums are linked to string values that correspond to keys in our CMS-system. Initially, we tried a simple ...

Navigating through a mergeMap observable with an undefined value

In my Angular 6 app, I have a class that attaches API tokens to every http request using the getIdToken() method. If the token retrieval is successful, everything works fine. However, if it fails, my app will stop functioning. I need help with handling th ...

Encountering a module resolve error when a tsx file is added to the project item group

After setting up an asp.net core project with a react template and configuring Typescript, I created a simple file named Test.tsx with the following code: import React from 'react'; class Test extends React.Component { render() { r ...

What could be causing the error with the async pipe: "InvalidPipeArgument: '[object Object],[object Object],' for the pipe 'AsyncPipe'?"

I am working on implementing search functionality in a table using ng-bootstrap. However, I am encountering an error with the async pipe that says "InvalidPipeArgument: '[object Object],[object Object],[object Object],[object Object],[object Object]&a ...

Leveraging Observables for Angular Drag and Drop Functionality

Struggling to use an Observable as the data source for a material drag and drop feature. Working on a kanban board with swimlanes containing movable items that need backend updates. Planning to implement socket.io for real-time item movement in the shared ...

Tips for preventing code duplication across various components in Angular 5

Within my angular application, there exist multiple components. Interestingly, two of these components share almost identical code, except for one component that includes additional button tags with unique logic while the rest of the code remains consist ...