Angular - 默认情况下选择的下拉列表中的标记选项

时间:2017-05-04 14:52:53

标签: javascript angular

我在将正确选项自动设置为selected时遇到问题。我怀疑原因可能是因为Angular不理解price.currencylet currency of currencies是同一个对象。

<select [(ngModel)]="price.currency" class="form-control">
    <option *ngFor="let currency of currencies" [ngValue]="currency">
        {{currency.iso_code}}
    </option>
</select>

我已经为pricecurrency创建了模型类,如下所示:

export class ProductPrice {
    id: number;
    product: number;
    price: number;
    taxrule: Taxrule;
    currency: Currency;
}

当我获取currencies的列表时,我将其转换为Currency[]列表。

最后......我还尝试将[selected]="price.currency.id == currency.id"参数添加到<option>而没有任何结果。可能是因为ngValue会覆盖它。

想法?

1 个答案:

答案 0 :(得分:1)

如您所知,无法从price.currency数组中识别currencies。您可以通过在这两个值之间创建引用来绑定这两个值。您可以在收到货币(和price)后执行此操作,例如:

this.price.currency = this.currencies.find(x => x.id == this.price.currency.id)

这是 Demo

相关问题