首页 > 解决方案 > 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.

标签: angular

解决方案


您需要使用空字符串初始化 formControl,然后一切都应该按预期工作。问题是formControl有一个值null但是占位符选项有一个空字符串的值

group = new FormGroup({
 configuredControlName: new FormControl(""),
});

或者,您可以将占位符的值与 null 值绑定,它也可以按预期工作。

<option [value]="null">{{ config.placeholder }}</option>

演示


推荐阅读