2017-07-02 15 views
0

我正在嘗試重寫用於呈現html select元素的列表,以使其鍵與列表對象類型的主標識符匹配。當重新映射源數組鍵時,Angular 4 ngFor不起作用

export class Industry { 
    constructor(
    public industryId?: number, 
    public code?: number, 
    public description?: string 
) { } 
} 

以我形式:

<select formControlName="industryId" class="form-control"> 
    <option *ngFor="let i of industries" [ngValue]="i.industryId">{{i.description}}</option> 
</select> 

當我分配,我從服務一切都很好,但是當我它重寫到一個關聯數組所以鍵它呈現主要標識符匹配獲得數組具有正確的選項數量但沒有值的選擇列表。

private getIndustries() { 
    this.industryService.getIndustries() 
    .subscribe(
     industries => { 
     // this works 
     this.industries = industries; 

     // this does not work 
     this.industries = []; 
     for (let item of industries) { 
      this.industries[item['industryId']] = item; 
     } 
    }); 
} 
+1

不能使用對象映射與ngFor。它應該爲你提出一個錯誤。 – cgTag

+1

你可以嘗試使用一個Map類,然後在你的模板中使用'industries.values()' – cgTag

+0

你並沒有將任何值加入你的行業數組變量 – Aravind

回答

0

在JS中沒有關聯數組的概念。你不能馬上做這件事。把它變成對象數組。在對象,你可以動態地添加鍵,然後訪問它像 這個..

對於如:

this.industry = []; 
    this.obj = {}; 
    for (let item of industries) { 
      this.obj[item['industryId']] = item; 
     }; 
In the view you can use ngFor to iterate get the value as follows... 
    this.industry.push(obj);