You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular的select控件中通过索引设置默认选中选项

你可以通过绑定selected属性配合循环下标实现需求,不需要修改原有TS逻辑和change事件绑定,修改后的代码如下:

<select class="noBorder additionalSelectStyle" name="filter_for" (change)="OnSerialChanged($event.target)">
    <option 
        *ngFor="let serial of tools.Attributes.Serials; let i = index"
        [selected]="i === nMyIndex"
    >
        {{serial}}
    </option>
</select>

改动点说明:

  • 在*ngFor指令中新增let i = index声明,获取当前循环项对应的数组下标
  • 给<option>标签添加[selected]属性绑定,当下标等于你定义的nMyIndex时自动选中当前项

如果nMyIndex是异步赋值的也无需额外处理,Angular的响应式绑定会在值更新后自动同步选中状态。

内容的提问来源于stack exchange,提问作者user3738290

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 06:09:01