2016-05-17 23 views
2

我的項目中有2個對象:a companyuser。我有一個表單,用戶可以更新他的個人資料。他可以更新的其中一件事是國家。現在顯示我使用下拉列表的國家。如果在Angular2中滿足條件,請在下拉列表中設置所選屬性

我想設置selected屬性在其中countryname等於user的實際country的選項。 (country.name==user.country

這是我所嘗試過的,但它似乎沒有工作。

<select> 
    <option *ngFor="#c of countries" [ngStyle]="setStyles()" [ngValue]="c">{{c.name}}</option>   
</select> 

setStyles(){ 
    let styles; 
    if (this.companies[i].name == this.user.country) { 
     styles = { 
      'selected' 
     } 
    return styles; 
} 

回答

5

我會嘗試以下方法:

<select> 
    <option *ngFor="#c of countries" 
     [attr.selected]="c.name == user.country ? true : null" 
     [ngValue]="c"> 
    {{c.name}} 
    </option> 
</select> 

我認爲這是你需要的屬性,而不是一個風格。

+0

感謝它的作品,但不是每個用戶,但我想我需要調整我的一些代碼。 – Claudiu

相關問題