首页 > 解决方案 > Angular ngFor 选择默认显示对象值的选项

问题描述

假设我有一个对象 statusOptions=['Approved', 'Waiting', 'Rejected']

在标记中,我们有:

<div *ngFor="let myObject of objects">
    <select (change)="updateStatus($event.target.value)">
       <option selected>{{myObject.status}}</option>
       <option *ngFor="let status of statusOptions">{{status}}</option>
    </select>
<div>

我如何将对象的当前状态显示为默认选定值?截至目前,它将复制并且下拉列表将显示['Approved', 'Waiting', 'Rejected', 'Approved']对象的当前状态是否为'Approved'

我不需要两种方式绑定,因为我只是获取更改的值并更新我的数据库。

标签: javascriptangularhtml-select

解决方案


通过在选项中设置 [attr.selected] 来解决它。

<div *ngFor="let myObject of objects">
<select (change)="updateStatus($event.target.value)">
   <option *ngFor="let status of statusOptions" [attr.selected]="transaction.status === status ? true : null">{{status}}</option>
</select>


推荐阅读