Reputation: 2357
I am trying to create dynamic ngModel within ngFor, I have an object array of the phone numbers which I need to bind with the form element & user can update that details, below is my code:
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>
So here [(ngModel)]="phone.label"
is not binding properly, values are not getting updated in the object
Upvotes: 2
Views: 5818
Reputation: 50643
Use NgValue
directive instead of value when you're working with select and NgModel
directive, and you should also add [ngModelOptions]="{ standalone : true }"
to your inputs to prevent them being added to same FormGroup
instance if you are using forms:
<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 }">
Upvotes: 2