Angular 2动态创建选择和设置选定选项(编辑操作)

时间:2016-10-20 08:43:55

标签: angular

我试图编辑用户。该用户具有非原始数组的机器。在编辑时,我想用select选项创建新元素,并将select选项设置为来自用户对象的值:

export class User{
    constructor(
        private id: number,
        private name: string,
        private machines: Machine[]
    ){}
}

export class Machine{
    constructor(
        private id: number,
        private name: string,
        private price: string
    ){}
}

得到了json:

users =[  
        {  
            "id":1,
            "name":"Mike",
            "machines":[  
                {  
                    "id":1,
                    "name":"bike",
                    "price":"10"
                },
                {  
                    "id":2,
                    "name":"boat",
                    "price":"100"
                }
            ]
        }
    ]
machines =[  
        {  
            "id":1,
            "name":"bike",
            "price":"10"
        },
        {  
            "id":2,
            "name":"boat",
            "price":"100"
        },
        {  
            "id":3,
            "name":"car",
            "price":"50"
        }
    ]

在编辑时,我想从用户设置选择值到机器的相应对象。

<div *ngFor="let machine of user.machines;  let i = index">
    <label>Pick machine</label>
    <div>
        <select name="machine" [(ngModel)]="user.machines[i]">
            <option *ngFor='let mach of machines' [ngValue]='mach' >{{mach.name}}</option>
        </select>
    </div>
</div>

问题在于:

enter image description here

两个选择选项都设置为最后一个。

更新(解决方案):

忘记提及,div在Template-Driven form内。

<form #f="ngForm" *ngIf="user" (submit)="updateUser(f.valid)" novalidate>
    <div *ngFor="let machine of user.machines;  let i = index">
        <label>Pick machine</label>
        <div>
            <select name="machine" [(ngModel)]="user.machines[i]">
                <option *ngFor='let mach of machines' [ngValue]='mach' >{{mach.name}}</option>
            </select>
        </div>
    </div>
</form>

如果在表单中实际提交了元素名称。

  

每个input元素都有一个Angular所需的name属性   用表单注册控件的表单。

通过添加唯一名称我解决了我的问题:

<select name="machine_{{i}}" [(ngModel)]="user.machines[i]">
                <option *ngFor='let mach of machines' [ngValue]='mach' >{{mach.name}}</option>

1 个答案:

答案 0 :(得分:-1)

您应该设置数组特定索引的ngModel的值:

 <div *ngFor="let machine of user.machines;  let i = index">
        <label>Pick machine</label>
        <div>
            <select name="machine"  [(ngModel)]="machine.id">
              //or you can set the 'id' direct
               <option *ngFor='let mach of machines' [ngValue]='mach' >{{mach.name}}</option>
            </select>
        </div>
    </div>