When submitting the form, an error occurs when trying to repopulate the data back to the form:
ERROR TypeError: Cannot read property 'id' of undefined
This is in reference to the code snippet:
<select [(ngModel)]="insurer.group.id" name="group" id="group">
Template:
<form #insurerForm="ngForm" (ngSubmit)="save(insurerForm)">
{{insurer|json}}
<select [(ngModel)]="insurer.group.id" name="group" id="group">
<option *ngFor="let group of groups"
[value]="group.id"
[selected]="insurer.group ? insurer.group.id === group.id : null">
{{group.name}}
</option>
</select>
<button type="submit" class="dd_button">Save</button>
</form>
Insurer object:
{
"is_admin": null,
"type": "insurer",
"group": {
"id": 13,
"email": null,
"name": "Generic"
}
...
}
Component:
export class InsurerDetailsComponent implements OnInit {
constructor(
private route: ActivatedRoute,
private apiService: ApiService,
private location: Location
) { }
ngOnInit(): void {
this.getInsurer();
}
groups: Group[];
insurer: Insurer;
getInsurer(): void {
const id = +this.route.snapshot.paramMap.get('id');
this.apiService.getOne(id, 'insurer', 'group').subscribe(insurer => {
this.insurer = insurer;
});
this.apiService.getMany('group').subscribe(groups =>
{
this.groups = groups
});
}
save(form: NgForm): void {
console.log('trying to save data: ', this.insurer);
console.log('form save data: ', form.value);
// this.apiService.update('insurer', this.insurer.id, form.value).subscribe(insurer => this.insurer = insurer);
}
}
I am encountering difficulties with what seems to be the form attempting to repopulate using the submitted form data. The issue lies in ngModel listening for insurer.group.id
, which does not exist. I tried changing ngModel to [(ngModel)]="group.id"
and [(ngModel)]="group"
, but it did not populate on page load.
I attempted to inspect the insurer object by displaying it as JSON with {{insurer|json}}
, but I do not see any changes after saving. I am unsure how to debug with accurate data.
I also tried updating the values of the insurer object hoping it would reflect with the following code:
save(form: NgForm): void {
this.insurer.group.id = form.value.group;
}
I am unsure about how to resolve the error and maintain the data populating on initial load. Modifying [(ngModel)]="insurer.group.id"
to [(ngModel)]="group"
resolves the error, but then the data is not set upon load even if I adjust the value
attribute accordingly.