gpt4 book ai didi

forms - Angular2 react 形式选择如何设置无效?

转载 作者:太空狗 更新时间:2023-10-29 18:25:32 26 4
gpt4 key购买 nike

我在我的应用中使用响应式表单。在某种形式下,我想显示一个required (Validators.required) select like this:

<select class="form-control"
[id]="dformControl.key"
[formControlName]="dformControl.key"
[multiple]="dformControl.multiple">

<option *ngIf="!dformControl.value"
value="undefined">
Choose ...
</option>

<option *ngFor="let opt of dformControl.options"
[value]="opt.value"
[selected]="dformControl.value == opt.value">
{{opt.label}}
</option>

</select>

问题是无论我使用 value="undefined" 还是 value="" 表单控件仍然设置为有效,因为它有一个值。不要在 value="Choose ..." 中显示 value 属性结果。

我是否以错误的方式将 select 与响应式(Reactive)表单一起使用,或者我如何才能使选项“选择...”不有效

最佳答案

将选择控件的初始值分配给 null 就可以了。试试下面,

  model_property = null

....
this.fb.group({
....
'control_key' : [this.model_property, Validators.required]
...
})

检查这个Plunker!! ,查看 app/reactive/hero-form-reactive.component.ts 文件。

我更新了 Plunker包括在下面,它似乎在工作,

    <select id="power" class="form-control"
formControlName="power" required >

// see the value is set to empty,
<option value="">Choose...</option>

<option *ngFor="let p of powers" [value]="p">{{p}}</option>
</select>

enter image description here

希望这对您有所帮助!

关于forms - Angular2 react 形式选择如何设置无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43075622/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com