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?