How to obtain nested object correctly from NgForm?

57 views Asked by At

I need to obtain keyvalue correctly from ngForm.

I have a User interface in Angular like this:

export interface User {
 id: int; 
 name: string; 
 surname: string; 
 school: School;  
}

And School interface like this:

{
 id: int;
 name: string; 
 address: string; 
}

I use *ngFor keyvalue to get key and value and i need to put them inside an <input/> tag like this:

<form #myForm="ngForm">
<div *ngFor="let item of user | keyvalue">
<input ngModel="{{item?.value}}" name="{{item?.key}}" >
</form>

when i call in my component myForm.value,for example with console.log(myForm.value), the result is like this :

{ 
 id: "someValue"
 name:"someValue" 
 surname: "someValue" 
 school: "[object Object]" 
}

but i need it was like this:

{ 
 id: "someValue"  
 name:"someValue" 
 surname: "someValue" 
 school: {          
           id:"someValue"           
           name: "someValue"           
           address: "someValue"          
          } 
}

How can i access and get correctly those nested key-value in school? Thank you!

1

There are 1 answers

1
Carlac On

I asked to chatGPT and it solved it for me. The solution is binding values with square brackets:

<input type="hidden" [ngModel]="item?.value" [name]="item?.key" >