ng用于在Angular 2中的键值对象的下拉列表中填充选项

时间:2017-11-24 00:09:35

标签: angular

如何使用ngFor在Angular 2中的键值对象的下拉列表中填充选项.json位于下方。

   {
     "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"
    }

我需要使用ngfor为就业,电话和移民填充3个下拉选项。 Angular 2

2 个答案:

答案 0 :(得分:3)

所以你必须根据以下三个对象渲染3个下拉列表:

obj.employment
obj.citizenship
obj.phone

其中obj

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"
   }
}

我在互联网上找到了一个链接,认为这正是你想要的

Looping Over Object Properties in Angular 2’s ngFor

注意:您应该将phone属性的格式设置为employmentcitizenship

答案 1 :(得分:0)

  

希望这有助于你

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' }
        ]
    }

和用户

user = { employmentId: 0, citizenshipId: 1, phone: 'work'};

在模板中使用

 <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>