Angular ngIf将选择的属性添加到value为字符串的选项 更新:使用value属性中的值更新:使用[(ngModel)]

问题描述

我想将selected属性动态添加option下拉列表的select中。

像这样

 <select name="gcodeProfile">
        <option value="HT Translucent F WF 500 um.gcode.profile" *ngIf='[attr.value] === {{resinFiletoLoad.gcodeProfile}}; [attr.selected] = true'>HT Translucent F WF 500 um.gcode.profile</option>
        <option value="HT Translucent F WF 500 um.gcode.profile-niki-safe" *ngIf='[attr.value] === {{resinFiletoLoad.gcodeProfile}}; [attr.selected] = true'>HT Translucent F WF 500 um.gcode.profile-niki-safe</option>
 </select>

哪里

resinFiletoLoad.gcodeProfile = 'HT Translucent F WF 500 um.gcode.profile';

解决方法

该条件实际上应绑定到[selected]属性。 attr属性不需要selected*ngIf指令也不需要。

尝试以下

<select name="gcodeProfile">
  <option 
    value="HT Translucent F WF 500 um.gcode.profile" 
    [selected]="resinFileToLoad.gcodeProfile === 'HT Translucent F WF 500 um.gcode.profile'"
  >
    HT Translucent F WF 500 um.gcode.profile
  </option>
  <option 
    value="HT Translucent F WF 500 um.gcode.profile-niki-safe" 
    [selected]="resinFileToLoad.gcodeProfile === 'HT Translucent F WF 500 um.gcode.profile-niki-safe'"
  >
    HT Translucent F WF 500 um.gcode.profile-niki-safe
  </option>
</select>

双引号中的单引号表示比较表达式中的字符串文字。

更新:使用value属性中的值

您可以将模板引用变量分配给选项,并在比较中访问它的值。尝试以下

<select name="gcodeProfile">
  <option #option1
    value="HT Translucent F WF 500 um.gcode.profile" 
    [selected]="resinFileToLoad.gcodeProfile === option1.value"
  >
    HT Translucent F WF 500 um.gcode.profile
  </option>
  <option #option2
    value="HT Translucent F WF 500 um.gcode.profile-niki-safe" 
    [selected]="resinFileToLoad.gcodeProfile === option2.value"
  >
    HT Translucent F WF 500 um.gcode.profile-niki-safe
  </option>
</select>

此处option1option2分别是选项1和2的模板参考变量。另外请注意,由于我们不再使用字符串文字,因此缺少单引号。

更新:使用[(ngModel)]

进行绑定

以上解决方案仅是针对较短下拉列表的快速修复。如果您需要可扩展的解决方案,则需要使用模板驱动的表单或反应式表单。

模板驱动的表单将是最快入门。除了使用valueselected属性,您还可以将默认值双向绑定到ngModel属性。

尝试以下

<select name="gcodeProfile" [(ngModel)]="resinFileToLoad.ZDir">
  <option> 1 </option>
  <option> 2 </option>
  <option> 3 </option>
  ...
</select>

现在,默认值绑定到resinFileToLoad.ZDir变量。因此,如果您在模板中执行类似{{ resinFileToLoad.ZDir }}的操作,则可以看到该值更改了accd。到下拉选择。如果您不希望出现这种情况,即保留resinFileToLoad.ZDir的值,则可以删除事件绑定并仅使用[ngModel]="resinFileToLoad.ZDir"