【问题标题】:Set the selected attribute in a dropdown list if the condition is met in Angular2如果在 Angular2 中满足条件,则在下拉列表中设置选定的属性
【发布时间】:2016-05-17 15:24:22
【问题描述】:

我的项目中有 2 个对象:companyuser。我有一个表格,用户可以在其中更新他的个人资料。他可以更新的一件事是国家。现在要显示我使用下拉列表的国家/地区。

我想在countryname 等于user 的实际country 的选项中设置selected 属性。 (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;
}

【问题讨论】:

    标签: forms drop-down-menu angular ng-style


    【解决方案1】:

    我会尝试以下方法:

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

    我认为这是您需要的属性,而不是样式。

    【讨论】:

    • 感谢它的工作,但不是每个用户,但我认为我需要调整我的一些代码。
    猜你喜欢
    • 2020-07-22
    • 1970-01-01
    • 2018-11-29
    • 2017-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-30
    • 1970-01-01
    相关资源
    最近更新 更多