简体   繁体   中英

ngModel two way binding for nested *ngFor in angular

My JSON looks like:

 "assets" : [ 
        {
            "resourceName" : "keyboard",
            "characteristics" : {
                "serialNo" : "abc123",
                "brand" : "DELL"
            }
        }, 
        {
            "resourceName" : "Domain Account"
        }
    ]

I am performing two way binding for displaying serialNo and brand values in html form as an input. Here's my html input code

 <table border="0"> <tr *ngFor="let r of assets; let i=index"> <td>{{r.resourceName | uppercase}} :</td> <td *ngFor="let key of r.characteristics | keys;let in=index; trackBy:keys" > {{key | uppercase}}: <input name="r.characteristics[key]" value="r.characteristics[key]" [(ngModel)]="r.characteristics[key]">&nbsp;&nbsp; </td> </tr> </table> 

In my form, for both the input fields, I am getting the value as DELL which is the value of brand. I want "abc123" to be displayed in serialNo field and DELL in brand field. Please refer to the plnkr for exact problem description.Thanks in advance.

First, I don't see in your snippet the pipe keys , it should be as the following:

@Pipe({ name: 'keys',  pure: false })

export class KeysPipe implements PipeTransform {
    transform(value: any, args: any[] = null): any {
        return Object.keys(value)
    }
}

Also, the name attribute should be set correctly:

HTML:

  <input name="someName[i]" [(ngModel)]="r.characteristics[key]">

plunker

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