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

Template Driven Form模板驱动表单中SelectOption预选功能失效问题

问题根因

问题出在两个核心点:

  1. 你给模板变量起的名字#currentFeedKey="ngModel"和外层ngFor循环的遍历变量currentFeedKey重名了,作用域被覆盖后,内层[selected]判断里拿到的currentFeedKey实际是ngModel控制器实例,和字符串比较永远为false,就算没接入表单这套逻辑也跑不通。
  2. 接入模板驱动表单并给select加上ngModel属性后,Angular表单模块会完全接管下拉框的选中状态,优先以ngModel绑定的值作为选中依据,你手动写的[selected]属性会被直接忽略,这是Angular表单的默认设计,所以之前没加ngModel的时候逻辑正常,加了就失效。

解决方案

  • 修改重名的模板变量,避免作用域覆盖
  • 去掉[selected]判断,直接给ngModel绑定你需要的默认值currentFeedKey,Angular会自动匹配和ngModel值相等的option进行选中,不需要手动控制selected属性
  • 补充优化:你原代码里select标签写了两个重复的class属性,可以合并

修改后完整代码

<div *ngFor="let currentFeedKey of currentFeedKeys" class="row mb-3">
  <label class="form-label col-sm-6 col-form-label">{{ currentFeedKey }}</label>
  <select 
    class="form-select col-sm-6" 
    [ngModel]="currentFeedKey" 
    name="{{currentFeedKey}}" 
    #currentFeedControl="ngModel"
  >
    <option>Bitte auswählen...</option>
    <option 
      *ngFor="let wantedFeedKey of wantedFeedKeys; let i = index" 
      [value]="wantedFeedKey"
    >{{ wantedFeedKey }}</option>
  </select>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 00:15:00