Reputation: 1
How use ngFor to populate options on a drop-down from key value object in Angular 2. json is below.
{
"employment": {
"0": "Employed",
"2": "Un-employed",
"3": "Retired",
"4": "Self"
"V": "V"
},
"citizenship": {
"0": "Citizen",
"1": "Immigrant",
"2": "Visa",
},
"phone": {
"HOME": "Home",
"CELL": "Cell",
"WORK": "Work"
}
I need to populate options for 3 dropdowns for employment , phone and immigration using ngfor. Angular 2
Upvotes: 0
Views: 3805
Reputation: 124
Hope this helps you
const obj = {
employment: [
{ Id: 0, text: 'Employed' },
{ Id: 1, text: 'Un-employed' },
{ Id: 2, text: 'Retired' },
{ Id: 3, text: 'Self' }
],
citizenship: [
{ Id: 0, text: 'Citizen' },
{ Id: 1, text: 'Immigrant' },
{ Id: 2, text: 'Visa' },
],
phone: [
{ Id: 0, text: 'Home' },
{ Id: 1, text: 'Cell' },
{ Id: 2, text: 'Work' }
]
}
and user as
user = { employmentId: 0, citizenshipId: 1, phone: 'work'};
use in template as
<select class="form-control" name="employment" #employment="ngModel" [(ngModel)]="user.employmentId" required >
<option value="" [disabled] selected>Employment</option>
<option *ngFor="let emp of obj.employment" [value]="emp.Id" [innerHTML]="emp.text" ></option>
</select>
<select class="form-control" name="citizenship" #citizenship="ngModel" [(ngModel)]="user.citizenshipId" required >
<option value="" [disabled] selected>Citizenship</option>
<option *ngFor="let citizen of obj.citizenship" [value]="citizen.Id" [innerHTML]="citizen.text" ></option>
</select>
<select class="form-control" name="phone" #phone="ngModel" [(ngModel)]="user.phone" required >
<option value="" [disabled] selected>Phone</option>
<option *ngFor="let num of obj.phone" [value]="num.Id" [innerHTML]="num.text" ></option>
</select>
Upvotes: 0
Reputation: 635
So you have to render 3 dropdowns based on three following objects:
obj.employment
obj.citizenship
obj.phone
where obj
is
var obj = {
"employment":{
"0":"Employed",
"2":"Un-employed",
"3":"Retired",
"4":"Self"
},
"citizenship":{
"0":"Citizen",
"1":"Immigrant",
"2":"Visa"
},
"phone":{
"HOME":"Home",
"CELL":"Cell",
"WORK":"Work"
}
}
I found a link on the internet and think this is exactly what you want
Looping Over Object Properties in Angular 2’s ngFor
Note: You should return the same format for phone
property as employment
or citizenship
Upvotes: 2