2

I have a property details which is a nested object. On clicking sign-in i get a form object which has values i want to set the values from the form into the nested object. Why cannot we use the normal .(dot) operator or the [] to chain and access the nested objects and their properties.

export class AppComponent {

    details:{
        city:string,
        dates:{
          date:Date,
          data:{
            name:string,
            comment:string
          }[]
        }[]
      }

     // this function is executed on submit of the form 

     onSignin(form:NgForm){

       console.log(form)
       this.details.city=form.value.city; // cannot set property 'city' of undifined
        console.log(this.details)
    }

}
2

2 Answers 2

0

I dont see any problem with your structure or code. It is possible that you may not be assigning the value correctly.

The below code gives me the correct output:

class Example {
  details: {
    city: string,
    dates: {
      date: Date,
      data: {
        name: string,
        comment: string
      }[]
    }[]
  } = {
      city: "Tokyo",
      dates: [
        {
          date: new Date(),
          data: [
            {
              name: "Stackoverflow",
              comment: "Hi"
            }
          ]
        }
      ]
    }


  getDetails() {
    console.log(this.details.city)
    this.details.city = "Hong Kong";
    console.log(this.details.city)
  }
}

new Example().getDetails();

This first prints "Tokyo" and then "Hong Kong". You have just defined details as variable and not assigned any value. Since details is currently undefined, you cannot directly set the value of only one its nested objects. You can set value for city, if details was assigned to any non null value.

Sign up to request clarification or add additional context in comments.

Comments

0

As the error message suggests, this.details is undefined. You need to create the object before you can set its properties. For example:

// A cast is required because `this.details` doesn't yet have the required properties.
this.details = {} as any;
this.details.city = form.value.city;
// ...

Or use an object literal instead of setting individual properties:

this.details = {city: form.value.city, dates: [ /*...*/ ]};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.