Reputation: 686
I am trying to add options in a html select inside a for loop. To get the selected option i am using [(ngModel)] but by default no option is selected.
Sample Code:
<table align="center">
<tr *ngFor="let d of data; let i = index">
<td>
<select id="status" [(ngModel)]="d.status" name="d.status" (change)="onStatusChange(i, d.id)">
<option *ngFor="let o of statusArray" [ngValue]="o">{{o.name}}</option>
</select>
</td>
</tr>
</table>
This is the component that I am using:
export class AboutComponent implements OnInit {
statusArray;
data;
constructor() { }
ngOnInit() {
this.statusArray = [
{
"id": 1,
"name": "Testing"
},
{
"id": 2,
"name": "Free Trial"
},
{
"id": 3,
"name": "Active/Paying"
}
];
this.data = [
{
"id": 2,
"status": {
"id": 1,
"name": "Testing"
},
"new": false
},
{
"id": 3,
"status": {
"id": 1,
"name": "Testing"
},
"new": false
},
{
"id": 4,
"status": {
"id": 2,
"name": "Free Trial"
},
"new": false
}
];
}
}
Output :
Here in the output i am getting the options in the list but default value is not selected:
Upvotes: 1
Views: 2304
Reputation: 11
I had the same issue. The solution was to make sure the name attribute of the select was different for each item.
Change
name="d.status"
to
name="d.status{{i}}"
Upvotes: 1
Reputation: 2023
you compare options to select by compareWith
property, If you are using angular 4.
HTML File :
<select [compareWith]="byAnimal" [(ngModel)]="selectedAnimal">
<option *ngFor="let animal of animals" [ngValue]="animal">
{{animal.type}}
</option>
</select>
TS File
byAnimal(item1,item2){
return item1.type == item2.type;
}
One of the best soltion from this link
Upvotes: 0
Reputation: 506
You can set it by default by using :
[(ngModel)]="d.status"
set the default value in d.status which you want to set.
Upvotes: 1
Reputation: 1502
Try to replace this:
<option *ngFor="let o of statusArray" [ngValue]="o">{{o.name}}</option>
with:
<option *ngFor="let o of statusArray" [ngValue]="o.id">{{o.name}}</option>
o
is an array, so no value exists for your option.
Upvotes: 1