2016-05-17 22 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

相关问题