添加formControlName会使默认值在Angular的窗体下拉菜单中消失 [英] Adding formControlName makes the default value disappear in my form's dropdown in Angular
本文介绍了添加formControlName会使默认值在Angular的窗体下拉菜单中消失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个select元素,看到了奇怪的事情,当我将formControlName添加到标签中时,初始值"month"不会显示,但是如果我删除它,它会显示但不能正确验证,因为它无法绑定.
I have this select element and I'm seeing something odd, when I add the formControlName to the tag the initial value "month" doesn't display, but if I remove it, it displays but doesn't validate correctly because it can't bind.
这是我的表格和html
Here is my form and the html
this.registerForm = this.fb.group({
gender: ['male'],
email: ['', [Validators.required, Validators.email]],
username: ['', [Validators.required, Validators.minLength(4), Validators.maxLength(10)]],
month: ['', Validators.required],
day: ['', Validators.required],
year: ['', Validators.required],
city: ['', Validators.required],
country: ['', Validators.required],
password: ['', [Validators.required, Validators.minLength(4), Validators.maxLength(10)]],
confirmPassword: ['', Validators.required]
}, {
validator: this.passwordMatchValidator
});
<div class="form-group col-4 col-sm-4 col-md-4">
<select [ngClass]="{'is-invalid': registerForm.get('month').errors && registerForm.get('month').dirty}" class="form-control" id="inputState1" formControlName="month">
<option disabled hidden selected>Month</option>
<option>Jan</option>
<option>Feb</option>
<option>Mar</option>
<option>Apr</option>
<option>May</option>
<option>Jun</option>
<option>Jul</option>
<option>Aug</option>
<option>Sep</option>
<option>Oct</option>
<option>Nov</option>
<option>Dec</option>
</select>
<div class="invalid-feedback" *ngIf="registerForm.get('month').dirty && registerForm.get('month').hasError('required')">Month required</div>
</div>
这就是我所看到的
formControlName ="month"
formControlName="month"
现在,当我删除
formControlName ="month"
formControlName="month"
我看到了
推荐答案
请在选项元素中添加value属性.
Please add the value attributes to the option elements.
<form [formGroup]="registerForm">
<div>
<input formControlName="email">
</div>
<div>
<select class="form-control" formControlName="month">
<option value="" hidden selected>Select a month</option>
<option value="1">Jan</option>
<option value="2">Feb</option>
</select>
</div>
</form>
此处的工作代码: https://angular-reactive-form-dropdown.stackblitz.io
这篇关于添加formControlName会使默认值在Angular的窗体下拉菜单中消失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文