angular - Angular select element looses default value when using [ngValue]
问题描述
I have select components that gets dynamically loaded with a reactive form
The select default value worked 100% like this:
<div class="selectComponent" [formGroup]="group">
<label>{{ config.label }}</label>
<select [formControlName]="config.name">
<option value="">{{ config.placeholder }}</option>
<option *ngFor="let option of config.options">
{{ option.name }}
</option>
</select>
</div>
But later I realized that even though I want option.name
to display in the dropdown list, I want a different value than the name like option.id
So I changed my code to:
<div class="selectComponent" [formGroup]="group">
<label>{{ config.label }}</label>
<select [formControlName]="config.name">
<option value="">{{ config.placeholder }}</option>
<option *ngFor="let option of config.options" [ngValue]="option.optionid">
{{ option.name }}
</option>
</select>
</div>
but now the default value is gone, and the box is just empty, even though the option value config.placeholder
is the first value in the drop-down list
Nothing I have tried have worked so far.
解决方案
您需要使用空字符串初始化 formControl,然后一切都应该按预期工作。问题是formControl
有一个值null
但是占位符选项有一个空字符串的值
group = new FormGroup({
configuredControlName: new FormControl(""),
});
或者,您可以将占位符的值与 null 值绑定,它也可以按预期工作。
<option [value]="null">{{ config.placeholder }}</option>
推荐阅读
- javascript - 承诺链如何引用下一个错误处理程序
- azure-service-fabric - 如何在 Azure Service Fabric 中使用变量替换
- javascript - 发出请求时如何在标头中包含移动设备详细信息?
- sql-server - SQL 数据读取器只读取 VB.net 中的第一行
- scala - 在某个 scala 对象中收集所有带注释的类名
- javascript - 获取网络应用上的未知内容
- python - Python将新数据迭代到嵌套字典中
- php - 如何处理 BLOB?
- ios - 为什么在我的自定义 UIView 类中没有调用 init(frame: CGRect)?
- c# - 使用 C#、Unity 游戏引擎在午夜创建重复事件