角度为2的动态ngModel

时间:2017-01-25 12:34:40

标签: angular angular2-forms

我正在尝试在ngFor中创建动态ngModel,我有一个电话号码的对象数组,我需要与表单元素&用户可以更新该详细信息,下面是我的代码:

phoneNumber = [{
    'type': 'mobile', 
    'number': '1234567', 
    'label': 'Personal'
}, {
    'type': 'landline', 
    'number': '64332222', 
    'label': 'Work'
}];

<div class="form-field-block" *ngFor="let phone of phoneNumber; let i = index ">
    <div class="form-group>
        <select name="phoneLabel" class="custom-select form-control-sm" [(ngModel)]="phone.label">
            <option value="Personal">Personal</option>
            <option value="Home">Home</option>
            <option value="Work">Work</option>
        </select>
        <select name="phoneFor" class="custom-select form-control-sm" [(ngModel)]="phone.type">
            <option value="mobile">Mobile</option>
            <option value="landline">Landline</option>
        </select>
    </div>
    <div class="form-group">
        <input type="text" class="form-control" name="number" placeholder="Phone Number" [(ngModel)]="phone.number">
    </div>
</div>

所以这里[(ngModel)]="phone.label"没有正确绑定,值没有在对象中更新

1 个答案:

答案 0 :(得分:2)

当您使用select和NgValue指令时,请使用NgModel指令而不是值,并且还应该在输入中添加[ngModelOptions]="{ standalone : true }"以防止它们被添加到同一FormGroup 1}}实例,如果您使用表单:

<select name="phoneLabel" class="custom-select form-control-sm" [(ngModel)]="phone.label" [ngModelOptions]="{ standalone : true }">
    <option [ngValue]="'Personal'">Personal</option>
    <option [ngValue]="'Home'">Home</option>
    <option [ngValue]="'Work'">Work</option>
</select>
<select name="phoneFor" class="custom-select form-control-sm" [(ngModel)]="phone.type" [ngModelOptions]="{ standalone : true }">
    <option [ngValue]="'mobile'">Mobile</option>
    <option [ngValue]="'landline'">Landline</option>
</select>
<input type="text" class="form-control" name="number" placeholder="Phone Number" [(ngModel)]="phone.number" [ngModelOptions]="{ standalone : true }">