当没有选择任何值时,我一直在努力验证带有默认“选择”选项的响应式(Reactive)表单到我的选择输入框。如果表单中存在值,那么我需要选择相应的值。
我使用响应式(Reactive)形式,下面是我的代码实现:
<select class="form-control" formControlName="environment" >
<option disabled [value]="null">-- Select --</option>
<option *ngFor="let ami of envs" [value]="ami.amiid">
{{ami.name}}
</option>
</select>
this.onlineTestForm = this._fb.group({
.
.
environment: ['', Validators.required],
.
.
});
//value is present in the model
(<FormControl>this.onlineTestForm.controls['environment'])
.setValue(this.model.environment, { onlySelf: true });
//value is not present in model
(<FormControl>this.onlineTestForm.controls['environment'])
.setValue('null', { onlySelf: true });
有没有更好的方法来实现上述目标?
最佳答案
您的问题在这里:
(<FormControl>this.onlineTestForm.controls['environment'])
.setValue('null', { onlySelf: true });
您正在设置字符串值'null'
而不是null
。字符串'null'
当然是一个有效值。
此外,您还可以将完整的对象设置为表单控件的值(如果存在),即使 environment
只需要 id,至少是您在模板中指定的内容:
[value]="ami.amiid"
<小时/>
我在这里看到两个选项可以“改进”您的代码。这些取决于 this.model
是否异步获取值。如果您知道初始化时 this.model
的值,则可以简单地执行以下操作:
environment: [this.model.environment || null,
Validators.required]
这里一定要记得将model
初始化为空对象,这样在model<中没有值的情况下才不会抛出
。 undefined
错误
如果model
值是异步设置的,则在获取该值后使用setValue
来设置该值:
this.onlineTestForm.controls.environment.setValue(...)
关于javascript - 响应式(Reactive)表单验证将选择输入框的默认 'select' 值视为有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45381331/