关于angular2形式:angular 2中的动态ngModel

 2021-04-27 

Dynamic ngModel in angular 2

我正在尝试在ngFor中创建动态ngModel,我有一个电话号码的对象数组,需要将其与form元素绑定


在使用select和NgModel指令时,

使用NgValue指令而不是值,并且还应该在输入中添加[ngModelOptions]="{ standalone : true }",以防止在使用时将它们添加到相同的FormGroup实例中形式:

1
2
3
4
5
6
7
8
9
10
<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 }">