简体   繁体   中英

Angular / Typescript Nested Objects (Model)

ERROR TypeError: Cannot read property 'applicants' of undefined

I am trying to run the following at component startup

application: application;
ngOnInit(): void {
  this.application.applicants[0].type = "1";    <-- don't think this is right
}

These are the two classes I created

export class application{
  applicants: applicants[];
  constructor(applicants: applicants[]){this.applicants = applicants;}
}

export class applicants{
  type: String;
  constructor(type: String){this.type = type;}
}

You need to instantiate the class application before you try and access the applicants. Because of how you have the constructor you will also need to instantiate an array of applicants. Try:

applicants: applicants[] = [new applicants("Applicant1"), new applicants("Applicant2"), new applicants("Applicant3")]
application: application = new application(applicants)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM