条件实际上应该绑定到[selected] 属性。 selected 属性不需要attr,*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>
这里option1 和option2 分别是选项1 和2 的模板引用变量。还要注意缺少单引号,因为我们不再使用字符串文字了。
更新:使用[(ngModel)]绑定
上述解决方案只是对短下拉菜单的快速修复。如果您需要可扩展的解决方案,则需要使用模板驱动的表单或响应式表单。
模板驱动的表单上手速度最快。除了使用value 和selected 属性外,您还可以将默认值双向绑定到ngModel 属性。
试试下面的
<select name="gcodeProfile" [(ngModel)]="resinFileToLoad.ZDir">
<option> 1 </option>
<option> 2 </option>
<option> 3 </option>
...
</select>
现在默认值绑定到resinFileToLoad.ZDir 变量。因此,如果您在模板中执行{{ resinFileToLoad.ZDir }} 之类的操作,您可以看到值发生了变化。到下拉选择。如果您不希望有这种行为,即保留 resinFileToLoad.ZDir 的值,您可以删除事件绑定并仅使用 [ngModel]="resinFileToLoad.ZDir"。